1. Project Clover database Thu Dec 20 2018 14:37:19 IST
  2. Package org.wso2.carbon.apimgt.impl.dao

File ApiMgtDAO.java

 

Coverage histogram

../../../../../../img/srcFileCovDistChart5.png
46% of files have more coverage

Code metrics

1,354
6,588
278
2
11,876
9,191
1,401
0.21
23.7
139
5.04

Classes

Class Line # Actions
ApiMgtDAO 135 6,588 0% 1,401 4,373
0.4680048546.8%
ApiMgtDAO.SubscriptionInfo 6902 0 - 0 0
-1.0 -
 

Contributing tests

This file is covered by 428 tests. .

Source view

1    /*
2    * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
3    *
4    * WSO2 Inc. licenses this file to you under the Apache License,
5    * Version 2.0 (the "License"); you may not use this file except
6    * in compliance with the License.
7    * You may obtain a copy of the License at
8    *
9    * http://www.apache.org/licenses/LICENSE-2.0
10    *
11    * Unless required by applicable law or agreed to in writing,
12    * software distributed under the License is distributed on an
13    * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14    * KIND, either express or implied. See the License for the
15    * specific language governing permissions and limitations
16    * under the License.
17    */
18   
19    package org.wso2.carbon.apimgt.impl.dao;
20   
21   
22    import com.google.common.base.Splitter;
23    import com.google.common.collect.Lists;
24    import org.apache.commons.lang.StringUtils;
25    import org.apache.commons.logging.Log;
26    import org.apache.commons.logging.LogFactory;
27    import org.wso2.carbon.apimgt.api.APIManagementException;
28    import org.wso2.carbon.apimgt.api.BlockConditionAlreadyExistsException;
29    import org.wso2.carbon.apimgt.api.SubscriptionAlreadyExistingException;
30    import org.wso2.carbon.apimgt.api.dto.ConditionDTO;
31    import org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO;
32    import org.wso2.carbon.apimgt.api.dto.UserApplicationAPIUsage;
33    import org.wso2.carbon.apimgt.api.model.API;
34    import org.wso2.carbon.apimgt.api.model.APIIdentifier;
35    import org.wso2.carbon.apimgt.api.model.APIKey;
36    import org.wso2.carbon.apimgt.api.model.APIStatus;
37    import org.wso2.carbon.apimgt.api.model.APIStore;
38    import org.wso2.carbon.apimgt.api.model.AccessTokenInfo;
39    import org.wso2.carbon.apimgt.api.model.Application;
40    import org.wso2.carbon.apimgt.api.model.ApplicationConstants;
41    import org.wso2.carbon.apimgt.api.model.BlockConditionsDTO;
42    import org.wso2.carbon.apimgt.api.model.Comment;
43    import org.wso2.carbon.apimgt.api.model.KeyManager;
44    import org.wso2.carbon.apimgt.api.model.Label;
45    import org.wso2.carbon.apimgt.api.model.LifeCycleEvent;
46    import org.wso2.carbon.apimgt.api.model.OAuthAppRequest;
47    import org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo;
48    import org.wso2.carbon.apimgt.api.model.Scope;
49    import org.wso2.carbon.apimgt.api.model.SubscribedAPI;
50    import org.wso2.carbon.apimgt.api.model.Subscriber;
51    import org.wso2.carbon.apimgt.api.model.Tier;
52    import org.wso2.carbon.apimgt.api.model.URITemplate;
53    import org.wso2.carbon.apimgt.api.model.policy.APIPolicy;
54    import org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy;
55    import org.wso2.carbon.apimgt.api.model.policy.BandwidthLimit;
56    import org.wso2.carbon.apimgt.api.model.policy.Condition;
57    import org.wso2.carbon.apimgt.api.model.policy.GlobalPolicy;
58    import org.wso2.carbon.apimgt.api.model.policy.HeaderCondition;
59    import org.wso2.carbon.apimgt.api.model.policy.IPCondition;
60    import org.wso2.carbon.apimgt.api.model.policy.JWTClaimsCondition;
61    import org.wso2.carbon.apimgt.api.model.policy.Pipeline;
62    import org.wso2.carbon.apimgt.api.model.policy.Policy;
63    import org.wso2.carbon.apimgt.api.model.policy.PolicyConstants;
64    import org.wso2.carbon.apimgt.api.model.policy.QueryParameterCondition;
65    import org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy;
66    import org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit;
67    import org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy;
68    import org.wso2.carbon.apimgt.impl.APIConstants;
69    import org.wso2.carbon.apimgt.impl.APIManagerConfiguration;
70    import org.wso2.carbon.apimgt.impl.ThrottlePolicyConstants;
71    import org.wso2.carbon.apimgt.impl.dao.constants.SQLConstants;
72    import org.wso2.carbon.apimgt.impl.dto.APIInfoDTO;
73    import org.wso2.carbon.apimgt.impl.dto.APIKeyInfoDTO;
74    import org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO;
75    import org.wso2.carbon.apimgt.impl.dto.APISubscriptionInfoDTO;
76    import org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO;
77    import org.wso2.carbon.apimgt.impl.dto.TierPermissionDTO;
78    import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO;
79    import org.wso2.carbon.apimgt.impl.factory.KeyManagerHolder;
80    import org.wso2.carbon.apimgt.impl.factory.SQLConstantManagerFactory;
81    import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder;
82    import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil;
83    import org.wso2.carbon.apimgt.impl.utils.APIUtil;
84    import org.wso2.carbon.apimgt.impl.utils.APIVersionComparator;
85    import org.wso2.carbon.apimgt.impl.utils.ApplicationUtils;
86    import org.wso2.carbon.apimgt.impl.utils.LRUCache;
87    import org.wso2.carbon.apimgt.impl.utils.RemoteUserManagerClient;
88    import org.wso2.carbon.apimgt.impl.workflow.WorkflowConstants;
89    import org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutorFactory;
90    import org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus;
91    import org.wso2.carbon.core.util.CryptoException;
92    import org.wso2.carbon.identity.core.util.IdentityTenantUtil;
93    import org.wso2.carbon.identity.core.util.IdentityUtil;
94    import org.wso2.carbon.identity.oauth.IdentityOAuthAdminException;
95    import org.wso2.carbon.user.core.util.UserCoreUtil;
96    import org.wso2.carbon.utils.DBUtils;
97    import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
98    import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
99   
100    import java.io.ByteArrayInputStream;
101    import java.io.IOException;
102    import java.io.InputStream;
103    import java.math.BigDecimal;
104    import java.nio.charset.Charset;
105    import java.sql.Connection;
106    import java.sql.PreparedStatement;
107    import java.sql.ResultSet;
108    import java.sql.SQLException;
109    import java.sql.Statement;
110    import java.sql.Timestamp;
111    import java.sql.Types;
112    import java.util.ArrayList;
113    import java.util.Arrays;
114    import java.util.Calendar;
115    import java.util.Collections;
116    import java.util.Comparator;
117    import java.util.HashMap;
118    import java.util.HashSet;
119    import java.util.Iterator;
120    import java.util.LinkedHashMap;
121    import java.util.LinkedHashSet;
122    import java.util.List;
123    import java.util.Map;
124    import java.util.Set;
125    import java.util.TreeMap;
126    import java.util.TreeSet;
127    import java.util.UUID;
128    import java.util.regex.Matcher;
129    import java.util.regex.Pattern;
130   
131   
132    /**
133    * This class represent the ApiMgtDAO.
134    */
 
135    public class ApiMgtDAO {
136    private static final Log log = LogFactory.getLog(ApiMgtDAO.class);
137    private static ApiMgtDAO INSTANCE = null;
138   
139    private boolean forceCaseInsensitiveComparisons = false;
140    private boolean multiGroupAppSharingEnabled = false;
141    private static boolean initialAutoCommit = false;
142   
 
143  18 toggle private ApiMgtDAO() {
144  18 APIManagerConfiguration configuration = ServiceReferenceHolder.getInstance()
145    .getAPIManagerConfigurationService().getAPIManagerConfiguration();
146   
147  18 String caseSensitiveComparison = ServiceReferenceHolder.getInstance().
148    getAPIManagerConfigurationService().getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_FORCE_CI_COMPARISIONS);
149  18 if (caseSensitiveComparison != null) {
150  18 forceCaseInsensitiveComparisons = Boolean.parseBoolean(caseSensitiveComparison);
151    }
152   
153  18 multiGroupAppSharingEnabled = APIUtil.isMultiGroupAppSharingEnabled();
154    }
155   
 
156  14 toggle public List<String> getAPIVersionsMatchingApiName(String apiName, String username) throws APIManagementException {
157  14 Connection conn = null;
158  14 PreparedStatement ps = null;
159  14 List<String> versionList = new ArrayList<String>();
160  14 ResultSet resultSet = null;
161   
162  14 String sqlQuery = SQLConstants.GET_VERSIONS_MATCHES_API_NAME_SQL;
163  14 try {
164  14 conn = APIMgtDBUtil.getConnection();
165  14 ps = conn.prepareStatement(sqlQuery);
166  14 ps.setString(1, apiName);
167  14 ps.setString(2, username);
168  14 resultSet = ps.executeQuery();
169  15 while (resultSet.next()) {
170  1 versionList.add(resultSet.getString("API_VERSION"));
171    }
172    } catch (SQLException e) {
173  0 handleException("Failed to get API versions matches API name" + apiName, e);
174    } finally {
175  14 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
176    }
177  14 return versionList;
178    }
179   
180   
181    /**
182    * Method to get the instance of the ApiMgtDAO.
183    *
184    * @return {@link ApiMgtDAO} instance
185    */
 
186  27969 toggle public static ApiMgtDAO getInstance() {
187  27969 if (INSTANCE == null) {
188  18 INSTANCE = new ApiMgtDAO();
189    }
190   
191  27969 return INSTANCE;
192    }
193   
194    /**
195    * Persist the details of the token generation request (allowed domains & validity period) to be used back
196    * when approval has been granted.
197    *
198    * @param dto DTO related to Application Registration.
199    * @param onlyKeyMappingEntry When this flag is enabled, only AM_APPLICATION_KEY_MAPPING will get affected.
200    * @throws APIManagementException if failed to create entries in AM_APPLICATION_REGISTRATION and
201    * AM_APPLICATION_KEY_MAPPING tables.
202    */
 
203  103 toggle public void createApplicationRegistrationEntry(ApplicationRegistrationWorkflowDTO dto, boolean onlyKeyMappingEntry)
204    throws APIManagementException {
205  103 Connection conn = null;
206  103 PreparedStatement ps = null;
207  103 PreparedStatement queryPs = null;
208  103 PreparedStatement appRegPs = null;
209  103 ResultSet resultSet = null;
210   
211  103 Application application = dto.getApplication();
212  103 Subscriber subscriber = application.getSubscriber();
213  103 String jsonString = dto.getAppInfoDTO().getOAuthApplicationInfo().getJsonString();
214   
215  103 String registrationQuery = SQLConstants.GET_APPLICATION_REGISTRATION_SQL;
216  103 String registrationEntry = SQLConstants.ADD_APPLICATION_REGISTRATION_SQL;
217  103 String keyMappingEntry = SQLConstants.ADD_APPLICATION_KEY_MAPPING_SQL;
218   
219  103 try {
220  103 conn = APIMgtDBUtil.getConnection();
221  103 conn.setAutoCommit(false);
222   
223  103 queryPs = conn.prepareStatement(registrationQuery);
224  103 queryPs.setInt(1, subscriber.getId());
225  103 queryPs.setInt(2, application.getId());
226  103 queryPs.setString(3, dto.getKeyType());
227  103 resultSet = queryPs.executeQuery();
228   
229  103 if (resultSet.next()) {
230  0 throw new APIManagementException("Application '" + application.getName() + "' is already registered.");
231    }
232   
233  103 if (!onlyKeyMappingEntry) {
234  103 appRegPs = conn.prepareStatement(registrationEntry);
235  103 appRegPs.setInt(1, subscriber.getId());
236  103 appRegPs.setString(2, dto.getWorkflowReference());
237  103 appRegPs.setInt(3, application.getId());
238  103 appRegPs.setString(4, dto.getKeyType());
239  103 appRegPs.setString(5, dto.getDomainList());
240  103 appRegPs.setLong(6, dto.getValidityTime());
241  103 appRegPs.setString(7, (String) dto.getAppInfoDTO().getOAuthApplicationInfo().getParameter("tokenScope"));
242  103 appRegPs.setString(8, jsonString);
243  103 appRegPs.execute();
244    }
245   
246  103 ps = conn.prepareStatement(keyMappingEntry);
247  103 ps.setInt(1, application.getId());
248  103 ps.setString(2, dto.getKeyType());
249  103 ps.setString(3, dto.getStatus().toString());
250  103 ps.execute();
251   
252  103 conn.commit();
253    } catch (SQLException e) {
254  0 try {
255  0 if (conn != null) {
256  0 conn.rollback();
257    }
258    } catch (SQLException e1) {
259  0 handleException("Error occurred while Rolling back changes done on Application Registration", e1);
260    }
261  0 handleException("Error occurred while creating an " +
262    "Application Registration Entry for Application : " + application.getName(), e);
263    } finally {
264  103 APIMgtDBUtil.closeStatement(queryPs);
265  103 APIMgtDBUtil.closeStatement(appRegPs);
266  103 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
267    }
268    }
269   
 
270  585 toggle public OAuthApplicationInfo getOAuthApplication(String consumerKey) throws APIManagementException {
271  585 OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
272  585 Connection conn = null;
273  585 PreparedStatement ps = null;
274  585 ResultSet rs = null;
275  585 String sqlQuery = SQLConstants.GET_OAUTH_APPLICATION_SQL;
276   
277  585 try {
278  585 conn = APIMgtDBUtil.getConnection();
279  585 ps = conn.prepareStatement(sqlQuery);
280  585 ps.setString(1, consumerKey);
281  585 rs = ps.executeQuery();
282  1170 while (rs.next()) {
283  585 oAuthApplicationInfo.setClientId(consumerKey);
284  585 oAuthApplicationInfo.setCallBackURL(rs.getString("CALLBACK_URL"));
285  585 oAuthApplicationInfo.setClientSecret(APIUtil.decryptToken(rs.getString("CONSUMER_SECRET")));
286  585 oAuthApplicationInfo.addParameter(ApplicationConstants.OAUTH_REDIRECT_URIS, rs.getString
287    ("CALLBACK_URL"));
288  585 oAuthApplicationInfo.addParameter(ApplicationConstants.OAUTH_CLIENT_NAME, rs.getString("APP_NAME"));
289  585 oAuthApplicationInfo.addParameter(ApplicationConstants.OAUTH_CLIENT_GRANT, rs.getString("GRANT_TYPES"));
290    }
291    } catch (SQLException e) {
292  0 handleException("Error while executing SQL for getting OAuth application info", e);
293    } catch (CryptoException e) {
294  0 handleException("Unable to decrypt consumer secret of consumer key " + consumerKey, e);
295    } finally {
296  585 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
297    }
298  585 return oAuthApplicationInfo;
299    }
300   
301    /**
302    * Get the creator of the OAuth App.
303    *
304    * @param consumerKey Client ID of the OAuth App
305    * @return {@code Subscriber} with name and TenantId set.
306    * @throws APIManagementException
307    */
 
308  100 toggle public Subscriber getOwnerForConsumerApp(String consumerKey) throws APIManagementException {
309  100 Connection conn = null;
310  100 PreparedStatement ps = null;
311  100 ResultSet rs = null;
312  100 String username;
313  100 Subscriber subscriber = null;
314   
315  100 String sqlQuery = SQLConstants.GET_OWNER_FOR_CONSUMER_APP_SQL;
316  100 try {
317  100 conn = APIMgtDBUtil.getConnection();
318  100 ps = conn.prepareStatement(sqlQuery);
319  100 ps.setString(1, consumerKey);
320  100 rs = ps.executeQuery();
321  200 while (rs.next()) {
322  100 username = rs.getString("USERNAME");
323  100 String domainName = rs.getString(APIConstants.IDENTITY_OAUTH2_FIELD_USER_DOMAIN);
324  100 String endUsernameWithDomain = UserCoreUtil.addDomainToName(username, domainName);
325  100 subscriber = new Subscriber(endUsernameWithDomain);
326  100 subscriber.setTenantId(rs.getInt("TENANT_ID"));
327    }
328    } catch (SQLException e) {
329  0 handleException("Error while executing SQL for getting User Id : SQL " + sqlQuery, e);
330    } finally {
331  100 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
332    }
333  100 return subscriber;
334    }
335   
336    /**
337    * Get Subscribed APIs for given userId
338    *
339    * @param userId id of the user
340    * @return APIInfoDTO[]
341    * @throws APIManagementException if failed to get Subscribed APIs
342    */
 
343  0 toggle public APIInfoDTO[] getSubscribedAPIsOfUser(String userId) throws APIManagementException {
344  0 List<APIInfoDTO> apiInfoDTOList = new ArrayList<APIInfoDTO>();
345  0 Connection conn = null;
346  0 PreparedStatement ps = null;
347  0 ResultSet rs = null;
348   
349    //identify logged in user
350  0 String loginUserName = getLoginUserName(userId);
351  0 String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(loginUserName);
352  0 int tenantId = APIUtil.getTenantId(loginUserName);
353   
354  0 String sqlQuery = SQLConstants.GET_SUBSCRIBED_APIS_OF_USER_SQL;
355  0 if (forceCaseInsensitiveComparisons) {
356  0 sqlQuery = SQLConstants.GET_SUBSCRIBED_APIS_OF_USER_CASE_INSENSITIVE_SQL;
357    }
358   
359  0 try {
360  0 conn = APIMgtDBUtil.getConnection();
361  0 ps = conn.prepareStatement(sqlQuery);
362  0 ps.setString(1, tenantAwareUsername);
363  0 ps.setInt(2, tenantId);
364  0 rs = ps.executeQuery();
365  0 while (rs.next()) {
366  0 APIInfoDTO infoDTO = new APIInfoDTO();
367  0 infoDTO.setProviderId(APIUtil.replaceEmailDomain(rs.getString("API_PROVIDER")));
368  0 infoDTO.setApiName(rs.getString("API_NAME"));
369  0 infoDTO.setVersion(rs.getString("API_VERSION"));
370  0 apiInfoDTOList.add(infoDTO);
371    }
372    } catch (SQLException e) {
373  0 handleException("Error while executing SQL", e);
374    } finally {
375  0 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
376    }
377  0 return apiInfoDTOList.toArray(new APIInfoDTO[apiInfoDTOList.size()]);
378    }
379   
380    /**
381    * Get API key information for given API
382    *
383    * @param apiInfoDTO API info
384    * @return APIKeyInfoDTO[]
385    * @throws APIManagementException if failed to get key info for given API
386    */
 
387  0 toggle public APIKeyInfoDTO[] getSubscribedUsersForAPI(APIInfoDTO apiInfoDTO) throws APIManagementException {
388  0 APIKeyInfoDTO[] apiKeyInfoDTOs = null;
389  0 Connection conn = null;
390  0 PreparedStatement ps = null;
391  0 ResultSet rs = null;
392  0 List<APIKeyInfoDTO> apiKeyInfoList = new ArrayList<APIKeyInfoDTO>();
393   
394  0 String sqlQuery = SQLConstants.GET_SUBSCRIBED_USERS_FOR_API_SQL;
395  0 try {
396  0 conn = APIMgtDBUtil.getConnection();
397  0 ps = conn.prepareStatement(sqlQuery);
398  0 ps.setString(1, APIUtil.replaceEmailDomainBack(apiInfoDTO.getProviderId()));
399  0 ps.setString(2, apiInfoDTO.getApiName());
400  0 ps.setString(3, apiInfoDTO.getVersion());
401  0 rs = ps.executeQuery();
402  0 while (rs.next()) {
403  0 String userId = rs.getString(APIConstants.SUBSCRIBER_FIELD_USER_ID);
404  0 APIKeyInfoDTO apiKeyInfoDTO = new APIKeyInfoDTO();
405  0 apiKeyInfoDTO.setUserId(userId);
406  0 apiKeyInfoList.add(apiKeyInfoDTO);
407    }
408  0 apiKeyInfoDTOs = apiKeyInfoList.toArray(new APIKeyInfoDTO[apiKeyInfoList.size()]);
409    } catch (SQLException e) {
410  0 handleException("Error while executing SQL", e);
411    } finally {
412  0 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
413    }
414  0 return apiKeyInfoDTOs;
415    }
416   
417    /**
418    * This method is to update the access token
419    *
420    * @param userId id of the user
421    * @param apiInfoDTO Api info
422    * @param statusEnum Status of the access key
423    * @throws APIManagementException if failed to update the access token
424    */
 
425  0 toggle public void changeAccessTokenStatus(String userId, APIInfoDTO apiInfoDTO, String statusEnum)
426    throws APIManagementException {
427  0 Connection conn = null;
428  0 PreparedStatement ps = null;
429   
430  0 String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(userId);
431  0 int tenantId = APIUtil.getTenantId(userId);
432   
433  0 String accessTokenStoreTable = APIConstants.ACCESS_TOKEN_STORE_TABLE;
434  0 accessTokenStoreTable = getAccessTokenStoreTableNameOfUserId(userId, accessTokenStoreTable);
435   
436  0 String sqlQuery = SQLConstants.CHANGE_ACCESS_TOKEN_STATUS_PREFIX +
437    accessTokenStoreTable + SQLConstants.CHANGE_ACCESS_TOKEN_STATUS_DEFAULT_SUFFIX;
438   
439  0 if (forceCaseInsensitiveComparisons) {
440  0 sqlQuery = SQLConstants.CHANGE_ACCESS_TOKEN_STATUS_PREFIX +
441    accessTokenStoreTable + SQLConstants.CHANGE_ACCESS_TOKEN_STATUS_CASE_INSENSITIVE_SUFFIX;
442    }
443   
444  0 try {
445  0 conn = APIMgtDBUtil.getConnection();
446  0 conn.setAutoCommit(false);
447   
448  0 ps = conn.prepareStatement(sqlQuery);
449  0 ps.setString(1, statusEnum);
450  0 ps.setString(2, tenantAwareUsername);
451  0 ps.setInt(3, tenantId);
452  0 ps.setString(4, APIUtil.replaceEmailDomainBack(apiInfoDTO.getProviderId()));
453  0 ps.setString(5, apiInfoDTO.getApiName());
454  0 ps.setString(6, apiInfoDTO.getVersion());
455   
456  0 int count = ps.executeUpdate();
457  0 if (log.isDebugEnabled()) {
458  0 log.debug("Number of rows being updated : " + count);
459    }
460  0 conn.commit();
461    } catch (SQLException e) {
462  0 try {
463  0 if (conn != null) {
464  0 conn.rollback();
465    }
466    } catch (SQLException e1) {
467  0 log.error("Failed to rollback the changeAccessTokenStatus operation", e1);
468    }
469  0 handleException("Error while executing SQL", e);
470    } finally {
471  0 APIMgtDBUtil.closeAllConnections(ps, conn, null);
472    }
473    }
474   
475   
 
476  104 toggle public boolean validateSubscriptionDetails(String context, String version, String consumerKey,
477    APIKeyValidationInfoDTO infoDTO) throws APIManagementException {
478  104 boolean defaultVersionInvoked = false;
479  104 String apiTenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(context);
480  104 if (apiTenantDomain == null) {
481  76 apiTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
482    }
483  104 int apiOwnerTenantId = APIUtil.getTenantIdFromTenantDomain(apiTenantDomain);
484    //Check if the api version has been prefixed with _default_
485  104 if (version != null && version.startsWith(APIConstants.DEFAULT_VERSION_PREFIX)) {
486  2 defaultVersionInvoked = true;
487    //Remove the prefix from the version.
488  2 version = version.split(APIConstants.DEFAULT_VERSION_PREFIX)[1];
489    }
490  104 String sql;
491  104 boolean isAdvancedThrottleEnabled = APIUtil.isAdvanceThrottlingEnabled();
492  104 if (!isAdvancedThrottleEnabled) {
493  3 if (defaultVersionInvoked) {
494  0 sql = SQLConstants.VALIDATE_SUBSCRIPTION_KEY_DEFAULT_SQL;
495    } else {
496  3 sql = SQLConstants.VALIDATE_SUBSCRIPTION_KEY_VERSION_SQL;
497    }
498    } else {
499  101 if (defaultVersionInvoked) {
500  2 sql = SQLConstants.ADVANCED_VALIDATE_SUBSCRIPTION_KEY_DEFAULT_SQL;
501    } else {
502  99 sql = SQLConstants.ADVANCED_VALIDATE_SUBSCRIPTION_KEY_VERSION_SQL;
503    }
504    }
505   
506  104 Connection conn = null;
507  104 PreparedStatement ps = null;
508  104 ResultSet rs = null;
509  104 try {
510  104 conn = APIMgtDBUtil.getConnection();
511  104 conn.setAutoCommit(true);
512  104 ps = conn.prepareStatement(sql);
513  104 ps.setString(1, context);
514  104 ps.setString(2, consumerKey);
515  104 if (!defaultVersionInvoked) {
516  102 ps.setString(3, version);
517    }
518  104 rs = ps.executeQuery();
519  104 if (rs.next()) {
520  102 String subscriptionStatus = rs.getString("SUB_STATUS");
521  102 String type = rs.getString("KEY_TYPE");
522  102 if (APIConstants.SubscriptionStatus.BLOCKED.equals(subscriptionStatus)) {
523  0 infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_BLOCKED);
524  0 infoDTO.setAuthorized(false);
525  0 return false;
526  102 } else if (APIConstants.SubscriptionStatus.ON_HOLD.equals(subscriptionStatus) || APIConstants
527    .SubscriptionStatus.REJECTED.equals(subscriptionStatus)) {
528  0 infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.SUBSCRIPTION_INACTIVE);
529  0 infoDTO.setAuthorized(false);
530  0 return false;
531  102 } else if (APIConstants.SubscriptionStatus.PROD_ONLY_BLOCKED.equals(subscriptionStatus) &&
532    !APIConstants.API_KEY_TYPE_SANDBOX.equals(type)) {
533  0 infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_BLOCKED);
534  0 infoDTO.setType(type);
535  0 infoDTO.setAuthorized(false);
536  0 return false;
537    }
538   
539  102 String tokenType = rs.getString("TOKEN_TYPE");
540  102 if (APIConstants.JWT.equals(tokenType)) {
541  0 infoDTO.setAuthorized(false);
542  0 return false;
543    }
544   
545  102 String apiProvider = rs.getString("API_PROVIDER");
546  102 String subTier = rs.getString("TIER_ID");
547  102 String appTier = rs.getString("APPLICATION_TIER");
548  102 infoDTO.setTier(subTier);
549  102 infoDTO.setSubscriber(rs.getString("USER_ID"));
550  102 infoDTO.setApplicationId(rs.getString("APPLICATION_ID"));
551  102 infoDTO.setApiName(rs.getString("API_NAME"));
552  102 infoDTO.setApiPublisher(apiProvider);
553  102 infoDTO.setApplicationName(rs.getString("NAME"));
554  102 infoDTO.setApplicationTier(appTier);
555  102 infoDTO.setType(type);
556   
557    //Advanced Level Throttling Related Properties
558  102 if (APIUtil.isAdvanceThrottlingEnabled()) {
559  99 String apiTier = rs.getString("API_TIER");
560  99 String subscriberUserId = rs.getString("USER_ID");
561  99 String subscriberTenant = MultitenantUtils.getTenantDomain(subscriberUserId);
562  99 int apiId = rs.getInt("API_ID");
563  99 int subscriberTenantId = APIUtil.getTenantId(subscriberUserId);
564  99 int apiTenantId = APIUtil.getTenantId(apiProvider);
565    //TODO isContentAware
566  99 boolean isContentAware = isAnyPolicyContentAware(conn, apiTier, appTier, subTier, subscriberTenantId, apiTenantId, apiId);
567  99 infoDTO.setContentAware(isContentAware);
568   
569    //TODO this must implement as a part of throttling implementation.
570  99 int spikeArrest = 0;
571  99 String apiLevelThrottlingKey = "api_level_throttling_key";
572  99 if (rs.getInt("RATE_LIMIT_COUNT") > 0) {
573  0 spikeArrest = rs.getInt("RATE_LIMIT_COUNT");
574    }
575   
576  99 String spikeArrestUnit = null;
577  99 if (rs.getString("RATE_LIMIT_TIME_UNIT") != null) {
578  0 spikeArrestUnit = rs.getString("RATE_LIMIT_TIME_UNIT");
579    }
580  99 boolean stopOnQuotaReach = rs.getBoolean("STOP_ON_QUOTA_REACH");
581  99 List<String> list = new ArrayList<String>();
582  99 list.add(apiLevelThrottlingKey);
583  99 infoDTO.setSpikeArrestLimit(spikeArrest);
584  99 infoDTO.setSpikeArrestUnit(spikeArrestUnit);
585  99 infoDTO.setStopOnQuotaReach(stopOnQuotaReach);
586  99 infoDTO.setSubscriberTenantDomain(subscriberTenant);
587  99 if (apiTier != null && apiTier.trim().length() > 0) {
588  0 infoDTO.setApiTier(apiTier);
589    }
590    //We also need to set throttling data list associated with given API. This need to have policy id and
591    // condition id list for all throttling tiers associated with this API.
592  99 infoDTO.setThrottlingDataList(list);
593    }
594  102 return true;
595    }
596  2 infoDTO.setAuthorized(false);
597  2 infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_RESOURCE_FORBIDDEN);
598    } catch (SQLException e) {
599  0 handleException("Exception occurred while validating Subscription.", e);
600    } finally {
601  104 try {
602  104 conn.setAutoCommit(false);
603    } catch (SQLException e) {
604   
605    }
606  104 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
607    }
608  2 return false;
609    }
610   
 
611  103 toggle private boolean isAnyPolicyContentAware(Connection conn, String apiPolicy, String appPolicy,
612    String subPolicy, int subscriptionTenantId, int appTenantId, int apiId) throws APIManagementException {
613  103 boolean isAnyContentAware = false;
614    // only check if using CEP based throttling.
615  103 ResultSet resultSet = null;
616  103 PreparedStatement ps = null;
617  103 String sqlQuery = SQLConstants.ThrottleSQLConstants.IS_ANY_POLICY_CONTENT_AWARE_SQL;
618   
619  103 try {
620  103 String dbProdName = conn.getMetaData().getDatabaseProductName();
621  103 ps = conn.prepareStatement(sqlQuery);
622  103 ps.setString(1, apiPolicy);
623  103 ps.setInt(2, subscriptionTenantId);
624  103 ps.setString(3, apiPolicy);
625  103 ps.setInt(4, subscriptionTenantId);
626  103 ps.setInt(5, apiId);
627  103 ps.setInt(6, subscriptionTenantId);
628  103 ps.setInt(7, apiId);
629  103 ps.setInt(8, subscriptionTenantId);
630  103 ps.setString(9, subPolicy);
631  103 ps.setInt(10, subscriptionTenantId);
632  103 ps.setString(11, appPolicy);
633  103 ps.setInt(12, appTenantId);
634  103 resultSet = ps.executeQuery();
635    // We only expect one result if all are not content aware.
636  103 if (resultSet == null) {
637  0 throw new APIManagementException(" Result set Null");
638    }
639  103 int count = 0;
640  103 if (resultSet.next()) {
641  103 count = resultSet.getInt(1);
642  103 if (count > 0) {
643  0 isAnyContentAware = true;
644    }
645    }
646    } catch (SQLException e) {
647  0 handleException("Failed to get content awareness of the policies ", e);
648    } finally {
649  103 APIMgtDBUtil.closeAllConnections(ps, null, resultSet);
650    }
651  103 return isAnyContentAware;
652    }
653   
 
654  34 toggle public void addSubscriber(Subscriber subscriber, String groupingId) throws APIManagementException {
655  34 Connection conn = null;
656  34 ResultSet rs = null;
657  34 PreparedStatement ps = null;
658  34 try {
659  34 conn = APIMgtDBUtil.getConnection();
660  34 conn.setAutoCommit(false);
661   
662  34 String query = SQLConstants.ADD_SUBSCRIBER_SQL;
663  34 ps = conn.prepareStatement(query, new String[]{"subscriber_id"});
664   
665  34 ps.setString(1, subscriber.getName());
666  34 ps.setInt(2, subscriber.getTenantId());
667  34 ps.setString(3, subscriber.getEmail());
668   
669  34 Timestamp timestamp = new Timestamp(subscriber.getSubscribedDate().getTime());
670  34 ps.setTimestamp(4, timestamp);
671  34 ps.setString(5, subscriber.getName());
672  34 ps.setTimestamp(6, timestamp);
673  34 ps.setTimestamp(7, timestamp);
674  34 ps.executeUpdate();
675   
676  34 int subscriberId = 0;
677  34 rs = ps.getGeneratedKeys();
678  34 if (rs.next()) {
679  34 subscriberId = Integer.parseInt(rs.getString(1));
680    }
681  34 subscriber.setId(subscriberId);
682  34 conn.commit();
683    } catch (SQLException e) {
684  0 if (conn != null) {
685  0 try {
686  0 conn.rollback();
687    } catch (SQLException e1) {
688  0 log.error("Error while rolling back the failed operation", e1);
689    }
690    }
691  0 handleException("Error in adding new subscriber: " + e.getMessage(), e);
692    } finally {
693  34 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
694    }
695    }
696   
 
697  0 toggle public void updateSubscriber(Subscriber subscriber) throws APIManagementException {
698  0 Connection conn = null;
699  0 PreparedStatement ps = null;
700  0 try {
701  0 conn = APIMgtDBUtil.getConnection();
702  0 conn.setAutoCommit(false);
703   
704  0 String query = SQLConstants.UPDATE_SUBSCRIBER_SQL;
705   
706  0 ps = conn.prepareStatement(query);
707  0 ps.setString(1, subscriber.getName());
708  0 ps.setInt(2, subscriber.getTenantId());
709  0 ps.setString(3, subscriber.getEmail());
710  0 ps.setTimestamp(4, new Timestamp(subscriber.getSubscribedDate().getTime()));
711  0 ps.setString(5, subscriber.getName());
712  0 ps.setTimestamp(6, new Timestamp(System.currentTimeMillis()));
713  0 ps.setInt(7, subscriber.getId());
714  0 ps.executeUpdate();
715   
716  0 conn.commit();
717    } catch (SQLException e) {
718  0 if (conn != null) {
719  0 try {
720  0 conn.rollback();
721    } catch (SQLException e1) {
722  0 log.error("Error while rolling back the failed operation", e1);
723    }
724    }
725  0 handleException("Error in updating subscriber: " + e.getMessage(), e);
726    } finally {
727  0 APIMgtDBUtil.closeAllConnections(ps, conn, null);
728    }
729    }
730   
 
731  0 toggle public Subscriber getSubscriber(int subscriberId) throws APIManagementException {
732  0 Connection conn = null;
733  0 ResultSet rs = null;
734  0 PreparedStatement ps = null;
735  0 try {
736  0 conn = APIMgtDBUtil.getConnection();
737  0 String query = SQLConstants.GET_SUBSCRIBER_SQL;
738   
739  0 ps = conn.prepareStatement(query);
740  0 ps.setInt(1, subscriberId);
741  0 rs = ps.executeQuery();
742  0 if (rs.next()) {
743  0 Subscriber subscriber = new Subscriber(rs.getString("USER_ID"));
744  0 subscriber.setId(subscriberId);
745  0 subscriber.setTenantId(rs.getInt("TENANT_ID"));
746  0 subscriber.setEmail(rs.getString("EMAIL_ADDRESS"));
747  0 subscriber.setSubscribedDate(new java.util.Date(rs.getTimestamp("DATE_SUBSCRIBED").getTime()));
748  0 return subscriber;
749    }
750    } catch (SQLException e) {
751  0 handleException("Error while retrieving subscriber: " + e.getMessage(), e);
752    } finally {
753  0 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
754    }
755  0 return null;
756    }
757   
 
758  119 toggle public int addSubscription(APIIdentifier identifier, String context, int applicationId, String status,
759    String subscriber) throws APIManagementException {
760  119 Connection conn = null;
761  119 ResultSet resultSet = null;
762  119 PreparedStatement ps = null;
763  119 PreparedStatement preparedStForInsert = null;
764  119 ResultSet rs = null;
765  119 int subscriptionId = -1;
766  119 int apiId;
767   
768  119 try {
769  119 conn = APIMgtDBUtil.getConnection();
770  119 conn.setAutoCommit(false);
771  119 apiId = getAPIID(identifier, conn);
772   
773    //Query to check if this subscription already exists
774  119 String checkDuplicateQuery = SQLConstants.CHECK_EXISTING_SUBSCRIPTION_SQL;
775  119 ps = conn.prepareStatement(checkDuplicateQuery);
776  119 ps.setInt(1, apiId);
777  119 ps.setInt(2, applicationId);
778   
779  119 resultSet = ps.executeQuery();
780   
781    //If the subscription already exists
782  119 if (resultSet.next()) {
783  1 String subStatus = resultSet.getString("SUB_STATUS");
784  1 String subCreationStatus = resultSet.getString("SUBS_CREATE_STATE");
785   
786  1 String applicationName = getApplicationNameFromId(applicationId);
787   
788  1 if ((APIConstants.SubscriptionStatus.UNBLOCKED.equals(subStatus) ||
789    APIConstants.SubscriptionStatus.ON_HOLD.equals(subStatus) ||
790    APIConstants.SubscriptionStatus.REJECTED.equals(subStatus)) &&
791    APIConstants.SubscriptionCreatedStatus.SUBSCRIBE.equals(subCreationStatus)) {
792   
793    //Throw error saying subscription already exists.
794  1 log.error("Subscription already exists for API " + identifier.getApiName() + " in Application " +
795    applicationName);
796  1 throw new SubscriptionAlreadyExistingException("Subscription already exists for API " +
797    identifier.getApiName() + " in Application " +
798    applicationName);
799  0 } else if (APIConstants.SubscriptionStatus.UNBLOCKED.equals(subStatus) && APIConstants
800    .SubscriptionCreatedStatus.UN_SUBSCRIBE.equals(subCreationStatus)) {
801  0 deleteSubscriptionByApiIDAndAppID(apiId, applicationId, conn);
802  0 } else if (APIConstants.SubscriptionStatus.BLOCKED.equals(subStatus) || APIConstants
803    .SubscriptionStatus.PROD_ONLY_BLOCKED.equals(subStatus)) {
804  0 log.error("Subscription to API " + identifier.getApiName() + " through application " +
805    applicationName + " was blocked");
806  0 throw new APIManagementException("Subscription to API " + identifier.getApiName() + " through " +
807    "application " + applicationName + " was blocked");
808    }
809    }
810   
811    //This query to update the AM_SUBSCRIPTION table
812  118 String sqlQuery = SQLConstants.ADD_SUBSCRIPTION_SQL;
813   
814    //Adding data to the AM_SUBSCRIPTION table
815    //ps = conn.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS);
816  118 preparedStForInsert = conn.prepareStatement(sqlQuery, new String[]{"SUBSCRIPTION_ID"});
817  118 if (conn.getMetaData().getDriverName().contains("PostgreSQL")) {
818  0 preparedStForInsert = conn.prepareStatement(sqlQuery, new String[]{"subscription_id"});
819    }
820   
821  118 preparedStForInsert.setString(1, identifier.getTier());
822  118 preparedStForInsert.setInt(2, apiId);
823  118 preparedStForInsert.setInt(3, applicationId);
824  118 preparedStForInsert.setString(4, status != null ? status : APIConstants.SubscriptionStatus.UNBLOCKED);
825  118 preparedStForInsert.setString(5, APIConstants.SubscriptionCreatedStatus.SUBSCRIBE);
826  118 preparedStForInsert.setString(6, subscriber);
827   
828  118 Timestamp timestamp = new Timestamp(System.currentTimeMillis());
829  118 preparedStForInsert.setTimestamp(7, timestamp);
830  118 preparedStForInsert.setTimestamp(8, timestamp);
831  118 preparedStForInsert.setString(9, UUID.randomUUID().toString());
832   
833  118 preparedStForInsert.executeUpdate();
834  118 rs = preparedStForInsert.getGeneratedKeys();
835  236 while (rs.next()) {
836    //subscriptionId = rs.getInt(1);
837  118 subscriptionId = Integer.parseInt(rs.getString(1));
838    }
839   
840    // finally commit transaction
841  118 conn.commit();
842    } catch (SQLException e) {
843  0 if (conn != null) {
844  0 try {
845  0 conn.rollback();
846    } catch (SQLException e1) {
847  0 log.error("Failed to rollback the add subscription ", e1);
848    }
849    }
850  0 handleException("Failed to add subscriber data ", e);
851    } finally {
852  119 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
853  119 APIMgtDBUtil.closeAllConnections(preparedStForInsert, null, rs);
854    }
855  118 return subscriptionId;
856    }
857   
858    /**
859    * Removes the subscription entry from AM_SUBSCRIPTIONS for identifier.
860    *
861    * @param identifier APIIdentifier
862    * @param applicationId ID of the application which has the subscription
863    * @throws APIManagementException
864    */
 
865  63 toggle public void removeSubscription(APIIdentifier identifier, int applicationId)
866    throws APIManagementException {
867  63 Connection conn = null;
868  63 ResultSet resultSet = null;
869  63 PreparedStatement ps = null;
870  63 int apiId = -1;
871  63 String uuid;
872  63 try {
873  63 conn = APIMgtDBUtil.getConnection();
874  63 conn.setAutoCommit(false);
875  63 apiId = getAPIID(identifier, conn);
876   
877  63 String subscriptionUUIDQuery = SQLConstants.GET_SUBSCRIPTION_UUID_SQL;
878   
879  63 ps = conn.prepareStatement(subscriptionUUIDQuery);
880  63 ps.setInt(1, apiId);
881  63 ps.setInt(2, applicationId);
882  63 resultSet = ps.executeQuery();
883   
884  63 if (resultSet.next()) {
885  62 uuid = resultSet.getString("UUID");
886  62 SubscribedAPI subscribedAPI = new SubscribedAPI(uuid);
887  62 removeSubscription(subscribedAPI, conn);
888    } else {
889  1 throw new APIManagementException("UUID does not exist for the given apiId:" + apiId + " and " +
890    "application id:" + applicationId);
891    }
892   
893  62 conn.commit();
894    } catch (SQLException e) {
895  0 if (conn != null) {
896  0 try {
897  0 conn.rollback();
898    } catch (SQLException ex) {
899  0 log.error("Failed to rollback the add subscription ", ex);
900    }
901    }
902  0 handleException("Failed to add subscriber data ", e);
903    } finally {
904  63 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
905    }
906    }
907   
908    /**
909    * Removes a subscription specified by SubscribedAPI object
910    *
911    * @param subscription SubscribedAPI object
912    * @param conn database connection object
913    * @throws APIManagementException
914    */
 
915  62 toggle public void removeSubscription(SubscribedAPI subscription, Connection conn) throws APIManagementException {
916  62 ResultSet resultSet = null;
917  62 PreparedStatement ps = null;
918  62 PreparedStatement preparedStForUpdateOrDelete = null;
919  62 String subStatus = null;
920   
921  62 try {
922  62 String subscriptionStatusQuery = SQLConstants.GET_SUBSCRIPTION_STATUS_BY_UUID_SQL;
923   
924  62 ps = conn.prepareStatement(subscriptionStatusQuery);
925  62 ps.setString(1, subscription.getUUID());
926  62 resultSet = ps.executeQuery();
927   
928  62 if (resultSet.next()) {
929  62 subStatus = resultSet.getString("SUB_STATUS");
930    }
931   
932    // If the user was unblocked, remove the entry from DB, else change the status and keep the entry.
933  62 String updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_SQL;
934  62 String deleteQuery = SQLConstants.REMOVE_SUBSCRIPTION_SQL;
935   
936  62 if (APIConstants.SubscriptionStatus.BLOCKED.equals(subStatus) || APIConstants.SubscriptionStatus
937    .PROD_ONLY_BLOCKED.equals(subStatus)) {
938  0 preparedStForUpdateOrDelete = conn.prepareStatement(updateQuery);
939  0 preparedStForUpdateOrDelete.setString(1, subscription.getUUID());
940    } else {
941  62 preparedStForUpdateOrDelete = conn.prepareStatement(deleteQuery);
942  62 preparedStForUpdateOrDelete.setString(1, subscription.getUUID());
943    }
944  62 preparedStForUpdateOrDelete.executeUpdate();
945    } catch (SQLException e) {
946  0 log.error("Failed to add subscriber data ", e);
947  0 handleException("Failed to add subscriber data ", e);
948    } finally {
949  62 APIMgtDBUtil.closeAllConnections(ps, null, resultSet);
950  62 APIMgtDBUtil.closeAllConnections(preparedStForUpdateOrDelete, null, null);
951    }
952    }
953   
954   
955    /**
956    * Removes a subscription by id by force without considering the subscription blocking state of the user
957    *
958    * @param subscription_id id of subscription
959    * @throws APIManagementException
960    */
 
961  0 toggle public void removeSubscriptionById(int subscription_id) throws APIManagementException {
962  0 Connection conn = null;
963  0 PreparedStatement ps = null;
964   
965  0 try {
966  0 conn = APIMgtDBUtil.getConnection();
967  0 conn.setAutoCommit(false);
968   
969  0 String sqlQuery = SQLConstants.REMOVE_SUBSCRIPTION_BY_ID_SQL;
970   
971  0 ps = conn.prepareStatement(sqlQuery);
972  0 ps.setInt(1, subscription_id);
973  0 ps.executeUpdate();
974   
975  0 conn.commit();
976    } catch (SQLException e) {
977  0 if (conn != null) {
978  0 try {
979  0 conn.rollback();
980    } catch (SQLException e1) {
981  0 log.error("Failed to rollback remove subscription ", e1);
982    }
983    }
984  0 handleException("Failed to remove subscription data ", e);
985    } finally {
986  0 APIMgtDBUtil.closeAllConnections(ps, conn, null);
987    }
988    }
989   
 
990  4 toggle public void removeAllSubscriptions(APIIdentifier apiIdentifier) throws APIManagementException {
991  4 Connection conn = null;
992  4 PreparedStatement ps = null;
993  4 int apiId;
994   
995  4 try {
996  4 conn = APIMgtDBUtil.getConnection();
997  4 conn.setAutoCommit(false);
998  4 apiId = getAPIID(apiIdentifier, conn);
999   
1000  4 String sqlQuery = SQLConstants.REMOVE_ALL_SUBSCRIPTIONS_SQL;
1001   
1002  4 ps = conn.prepareStatement(sqlQuery);
1003  4 ps.setInt(1, apiId);
1004  4 ps.executeUpdate();
1005   
1006  4 conn.commit();
1007    } catch (SQLException e) {
1008  0 if (conn != null) {
1009  0 try {
1010  0 conn.rollback();
1011    } catch (SQLException e1) {
1012  0 log.error("Failed to rollback remove all subscription ", e1);
1013    }
1014    }
1015  0 handleException("Failed to remove all subscriptions data ", e);
1016    } finally {
1017  4 APIMgtDBUtil.closeAllConnections(ps, conn, null);
1018    }
1019    }
1020   
 
1021  0 toggle public String getSubscriptionStatusById(int subscriptionId) throws APIManagementException {
1022   
1023  0 Connection conn = null;
1024  0 ResultSet resultSet = null;
1025  0 PreparedStatement ps = null;
1026  0 String subscriptionStatus = null;
1027   
1028  0 try {
1029  0 conn = APIMgtDBUtil.getConnection();
1030  0 String getApiQuery = SQLConstants.GET_SUBSCRIPTION_STATUS_BY_ID_SQL;
1031  0 ps = conn.prepareStatement(getApiQuery);
1032  0 ps.setInt(1, subscriptionId);
1033  0 resultSet = ps.executeQuery();
1034  0 if (resultSet.next()) {
1035  0 subscriptionStatus = resultSet.getString("SUB_STATUS");
1036    }
1037  0 return subscriptionStatus;
1038    } catch (SQLException e) {
1039  0 handleException("Failed to retrieve subscription status", e);
1040    } finally {
1041  0 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
1042    }
1043  0 return null;
1044    }
1045   
1046    /**
1047    * returns the SubscribedAPI object which is related to the subscriptionId
1048    *
1049    * @param subscriptionId subscription id
1050    * @return {@link SubscribedAPI} Object which contains the subscribed API information.
1051    * @throws APIManagementException
1052    */
 
1053  116 toggle public SubscribedAPI getSubscriptionById(int subscriptionId) throws APIManagementException {
1054  116 Connection conn = null;
1055  116 ResultSet resultSet = null;
1056  116 PreparedStatement ps = null;
1057   
1058  116 try {
1059  116 conn = APIMgtDBUtil.getConnection();
1060  116 String getSubscriptionQuery = SQLConstants.GET_SUBSCRIPTION_BY_ID_SQL;
1061  116 ps = conn.prepareStatement(getSubscriptionQuery);
1062  116 ps.setInt(1, subscriptionId);
1063  116 resultSet = ps.executeQuery();
1064  116 SubscribedAPI subscribedAPI = null;
1065  116 if (resultSet.next()) {
1066  116 APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(resultSet.getString
1067    ("API_PROVIDER")), resultSet.getString("API_NAME"), resultSet.getString("API_VERSION"));
1068   
1069  116 int applicationId = resultSet.getInt("APPLICATION_ID");
1070  116 Application application = getApplicationById(applicationId);
1071  116 subscribedAPI = new SubscribedAPI(application.getSubscriber(), apiIdentifier);
1072  116 subscribedAPI.setSubscriptionId(resultSet.getInt("SUBSCRIPTION_ID"));
1073  116 subscribedAPI.setSubStatus(resultSet.getString("SUB_STATUS"));
1074  116 subscribedAPI.setSubCreatedStatus(resultSet.getString("SUBS_CREATE_STATE"));
1075  116 subscribedAPI.setTier(new Tier(resultSet.getString("TIER_ID")));
1076  116 subscribedAPI.setUUID(resultSet.getString("UUID"));
1077  116 subscribedAPI.setApplication(application);
1078    }
1079  116 return subscribedAPI;
1080    } catch (SQLException e) {
1081  0 handleException("Failed to retrieve subscription from subscription id", e);
1082    } finally {
1083  116 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
1084    }
1085  0 return null;
1086    }
1087   
1088    /**
1089    * returns the SubscribedAPI object which is related to the UUID
1090    *
1091    * @param uuid UUID of Application
1092    * @return {@link SubscribedAPI} Object which contains the subscribed API information.
1093    * @throws APIManagementException
1094    */
 
1095  23 toggle public SubscribedAPI getSubscriptionByUUID(String uuid) throws APIManagementException {
1096  23 Connection conn = null;
1097  23 ResultSet resultSet = null;
1098  23 PreparedStatement ps = null;
1099   
1100  23 try {
1101  23 conn = APIMgtDBUtil.getConnection();
1102  23 String getSubscriptionQuery = SQLConstants.GET_SUBSCRIPTION_BY_UUID_SQL;
1103  23 ps = conn.prepareStatement(getSubscriptionQuery);
1104  23 ps.setString(1, uuid);
1105  23 resultSet = ps.executeQuery();
1106  23 SubscribedAPI subscribedAPI = null;
1107  23 if (resultSet.next()) {
1108  23 APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(resultSet.getString
1109    ("API_PROVIDER")), resultSet.getString("API_NAME"), resultSet.getString("API_VERSION"));
1110   
1111  23 int applicationId = resultSet.getInt("APPLICATION_ID");
1112  23 Application application = getApplicationById(applicationId);
1113  23 subscribedAPI = new SubscribedAPI(application.getSubscriber(), apiIdentifier);
1114  23 subscribedAPI.setUUID(resultSet.getString("UUID"));
1115  23 subscribedAPI.setSubscriptionId(resultSet.getInt("SUBSCRIPTION_ID"));
1116  23 subscribedAPI.setSubStatus(resultSet.getString("SUB_STATUS"));
1117  23 subscribedAPI.setSubCreatedStatus(resultSet.getString("SUBS_CREATE_STATE"));
1118  23 subscribedAPI.setTier(new Tier(resultSet.getString("TIER_ID")));
1119   
1120  23 Timestamp createdTime = resultSet.getTimestamp("CREATED_TIME");
1121  23 subscribedAPI.setCreatedTime(createdTime == null ? null : String.valueOf(createdTime.getTime()));
1122  23 try {
1123  23 Timestamp updated_time = resultSet.getTimestamp("UPDATED_TIME");
1124  23 subscribedAPI.setUpdatedTime(
1125  23 updated_time == null ? null : String.valueOf(updated_time.getTime()));
1126    } catch (SQLException e) {
1127    // fixing Timestamp issue with default value '0000-00-00 00:00:00'for existing applications created
1128  0 subscribedAPI.setUpdatedTime(subscribedAPI.getCreatedTime());
1129    }
1130  23 subscribedAPI.setApplication(application);
1131    }
1132  23 return subscribedAPI;
1133    } catch (SQLException e) {
1134  0 handleException("Failed to retrieve subscription from subscription id", e);
1135    } finally {
1136  23 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
1137    }
1138  0 return null;
1139    }
1140   
1141    /**
1142    * This method used tot get Subscriber from subscriberId.
1143    *
1144    * @param subscriberName id
1145    * @return Subscriber
1146    * @throws APIManagementException if failed to get Subscriber from subscriber id
1147    */
 
1148  686 toggle public Subscriber getSubscriber(String subscriberName) throws APIManagementException {
1149  686 Connection conn = null;
1150  686 Subscriber subscriber = null;
1151  686 PreparedStatement ps = null;
1152  686 ResultSet result = null;
1153   
1154  686 int tenantId = APIUtil.getTenantId(subscriberName);
1155   
1156  686 String sqlQuery = SQLConstants.GET_TENANT_SUBSCRIBER_SQL;
1157  686 if (forceCaseInsensitiveComparisons) {
1158  686 sqlQuery = SQLConstants.GET_TENANT_SUBSCRIBER_CASE_INSENSITIVE_SQL;
1159    }
1160   
1161  686 try {
1162  686 conn = APIMgtDBUtil.getConnection();
1163   
1164  686 ps = conn.prepareStatement(sqlQuery);
1165  686 ps.setString(1, subscriberName);
1166  686 ps.setInt(2, tenantId);
1167  686 result = ps.executeQuery();
1168   
1169  686 if (result.next()) {
1170  650 subscriber = new Subscriber(result.getString(APIConstants.SUBSCRIBER_FIELD_EMAIL_ADDRESS));
1171  650 subscriber.setEmail(result.getString("EMAIL_ADDRESS"));
1172  650 subscriber.setId(result.getInt("SUBSCRIBER_ID"));
1173  650 subscriber.setName(subscriberName);
1174  650 subscriber.setSubscribedDate(result.getDate(APIConstants.SUBSCRIBER_FIELD_DATE_SUBSCRIBED));
1175  650 subscriber.setTenantId(result.getInt("TENANT_ID"));
1176    }
1177    } catch (SQLException e) {
1178  0 handleException("Failed to get Subscriber for :" + subscriberName, e);
1179    } finally {
1180  686 APIMgtDBUtil.closeAllConnections(ps, conn, result);
1181    }
1182  686 return subscriber;
1183    }
1184   
 
1185  0 toggle public Set<APIIdentifier> getAPIByConsumerKey(String accessToken) throws APIManagementException {
1186  0 Connection connection = null;
1187  0 PreparedStatement ps = null;
1188  0 ResultSet result = null;
1189   
1190  0 String getAPISql = SQLConstants.GET_API_BY_CONSUMER_KEY_SQL;
1191   
1192  0 Set<APIIdentifier> apiSet = new HashSet<APIIdentifier>();
1193  0 try {
1194  0 connection = APIMgtDBUtil.getConnection();
1195  0 ps = connection.prepareStatement(getAPISql);
1196  0 String encryptedAccessToken = APIUtil.encryptToken(accessToken);
1197  0 ps.setString(1, encryptedAccessToken);
1198  0 result = ps.executeQuery();
1199  0 while (result.next()) {
1200  0 apiSet.add(new APIIdentifier(result.getString("API_PROVIDER"), result.getString("API_NAME"), result
1201    .getString("API_VERSION")));
1202    }
1203    } catch (SQLException e) {
1204  0 handleException("Failed to get API ID for token: " + accessToken, e);
1205    } catch (CryptoException e) {
1206  0 handleException("Failed to get API ID for token: " + accessToken, e);
1207    } finally {
1208  0 APIMgtDBUtil.closeAllConnections(ps, connection, result);
1209    }
1210  0 return apiSet;
1211    }
1212   
1213    /**
1214    * This method returns the set of APIs for given subscriber, subscribed under the specified application.
1215    *
1216    * @param subscriber subscriber
1217    * @param applicationName Application Name
1218    * @return Set<API>
1219    * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to get SubscribedAPIs
1220    */
 
1221  8 toggle public Set<SubscribedAPI> getSubscribedAPIs(Subscriber subscriber, String applicationName, String groupingId)
1222    throws APIManagementException {
1223  8 Set<SubscribedAPI> subscribedAPIs = new LinkedHashSet<SubscribedAPI>();
1224  8 Connection connection = null;
1225  8 PreparedStatement ps = null;
1226  8 ResultSet result = null;
1227  8 String sqlQuery = SQLConstants.GET_SUBSCRIBED_APIS_SQL;
1228   
1229  8 String whereClauseWithGroupId = " AND (APP.GROUP_ID = ? OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL)"
1230    + " AND SUB.USER_ID = ?))";
1231  8 String whereClauseWithGroupIdorceCaseInsensitiveComp = " AND (APP.GROUP_ID = ?"
1232    + " OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL) AND LOWER(SUB.USER_ID) = LOWER(?)))";
1233  8 String whereClause = " AND SUB.USER_ID = ? ";
1234  8 String whereClauseCaseSensitive = " AND LOWER(SUB.USER_ID) = LOWER(?) ";
1235   
1236  8 String whereClauseWithMultiGroupId = " AND ( (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM " +
1237    "AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?)) OR ( SUB.USER_ID = ? ))";
1238  8 String whereClauseWithMultiGroupIdCaseInsensitive = " AND ( (APP.APPLICATION_ID IN (SELECT APPLICATION_ID " +
1239    "FROM AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?)) OR ( LOWER(SUB.USER_ID) = LOWER" +
1240    "(?) ))";
1241   
1242  8 try {
1243  8 connection = APIMgtDBUtil.getConnection();
1244  8 if (groupingId != null && !"null".equals(groupingId) && !groupingId.isEmpty()) {
1245   
1246  0 if (multiGroupAppSharingEnabled) {
1247  0 if (forceCaseInsensitiveComparisons) {
1248  0 sqlQuery += whereClauseWithMultiGroupIdCaseInsensitive;
1249    } else {
1250  0 sqlQuery += whereClauseWithMultiGroupId;
1251    }
1252  0 String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
1253  0 String groupIdArr[] = groupingId.split(",");
1254   
1255  0 ps = fillQueryParams(connection, sqlQuery, groupIdArr, 3);
1256  0 int tenantId = APIUtil.getTenantId(subscriber.getName());
1257  0 ps.setInt(1, tenantId);
1258  0 ps.setString(2, applicationName);
1259  0 int paramIndex = groupIdArr.length + 2;
1260  0 ps.setString(++paramIndex, tenantDomain);
1261  0 ps.setString(++paramIndex, subscriber.getName());
1262    } else {
1263  0 if (forceCaseInsensitiveComparisons) {
1264  0 sqlQuery += whereClauseWithGroupIdorceCaseInsensitiveComp;
1265    } else {
1266  0 sqlQuery += whereClauseWithGroupId;
1267    }
1268  0 ps = connection.prepareStatement(sqlQuery);
1269  0 int tenantId = APIUtil.getTenantId(subscriber.getName());
1270  0 ps.setInt(1, tenantId);
1271  0 ps.setString(2, applicationName);
1272  0 ps.setString(3, groupingId);
1273  0 ps.setString(4, subscriber.getName());
1274    }
1275    } else {
1276  8 if (forceCaseInsensitiveComparisons) {
1277  8 sqlQuery += whereClauseCaseSensitive;
1278    } else {
1279  0 sqlQuery += whereClause;
1280    }
1281  8 ps = connection.prepareStatement(sqlQuery);
1282  8 int tenantId = APIUtil.getTenantId(subscriber.getName());
1283  8 ps.setInt(1, tenantId);
1284  8 ps.setString(2, applicationName);
1285  8 ps.setString(3, subscriber.getName());
1286    }
1287  8 result = ps.executeQuery();
1288   
1289  18 while (result.next()) {
1290  10 APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(result.getString
1291    ("API_PROVIDER")), result.getString("API_NAME"), result.getString("API_VERSION"));
1292   
1293  10 SubscribedAPI subscribedAPI = new SubscribedAPI(subscriber, apiIdentifier);
1294  10 subscribedAPI.setSubscriptionId(result.getInt("SUBS_ID"));
1295  10 subscribedAPI.setSubStatus(result.getString("SUB_STATUS"));
1296  10 subscribedAPI.setSubCreatedStatus(result.getString("SUBS_CREATE_STATE"));
1297  10 subscribedAPI.setUUID(result.getString("SUB_UUID"));
1298  10 subscribedAPI.setTier(new Tier(result.getString(APIConstants.SUBSCRIPTION_FIELD_TIER_ID)));
1299   
1300  10 Application application = new Application(result.getString("APP_NAME"), subscriber);
1301  10 application.setUUID(result.getString("APP_UUID"));
1302  10 subscribedAPI.setApplication(application);
1303  10 subscribedAPIs.add(subscribedAPI);
1304    }
1305    } catch (SQLException e) {
1306  0 handleException("Failed to get SubscribedAPI of :" + subscriber.getName(), e);
1307    } finally {
1308  8 APIMgtDBUtil.closeAllConnections(ps, connection, result);
1309    }
1310  8 return subscribedAPIs;
1311    }
1312   
 
1313  828 toggle public Integer getSubscriptionCount(Subscriber subscriber, String applicationName, String groupingId)
1314    throws APIManagementException {
1315  828 Integer subscriptionCount = 0;
1316  828 Connection connection = null;
1317  828 PreparedStatement ps = null;
1318  828 ResultSet result = null;
1319  828 int tenantId = APIUtil.getTenantId(subscriber.getName());
1320   
1321  828 try {
1322  828 connection = APIMgtDBUtil.getConnection();
1323   
1324  828 String sqlQuery = SQLConstants.GET_SUBSCRIPTION_COUNT_SQL;
1325  828 if (forceCaseInsensitiveComparisons) {
1326  828 sqlQuery = SQLConstants.GET_SUBSCRIPTION_COUNT_CASE_INSENSITIVE_SQL;
1327    }
1328   
1329  828 String whereClauseWithGroupId = " AND (APP.GROUP_ID = ? OR "
1330    + "((APP.GROUP_ID = '' OR APP.GROUP_ID IS NULL) AND SUB.USER_ID = ?)) ";
1331  828 String whereClauseWithMultiGroupId = " AND ( (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM " +
1332    "AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?)) OR ( SUB.USER_ID = ? ))";
1333  828 String whereClauseWithUserId = " AND SUB.USER_ID = ? ";
1334  828 String whereClauseCaseSensitive = " AND LOWER(SUB.USER_ID) = LOWER(?) ";
1335  828 String appIdentifier;
1336   
1337  828 boolean hasGrouping = false;
1338  828 if (groupingId != null && !"null".equals(groupingId) && !groupingId.isEmpty()) {
1339  0 if (multiGroupAppSharingEnabled) {
1340  0 String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
1341  0 sqlQuery += whereClauseWithMultiGroupId;
1342  0 String[] groupIdArr = groupingId.split(",");
1343   
1344  0 ps = fillQueryParams(connection, sqlQuery, groupIdArr, 3);
1345  0 ps.setString(1, applicationName);
1346  0 ps.setInt(2, tenantId);
1347  0 int paramIndex = groupIdArr.length + 2;
1348  0 ps.setString(++paramIndex, tenantDomain);
1349  0 ps.setString(++paramIndex, subscriber.getName());
1350    } else {
1351  0 sqlQuery += whereClauseWithGroupId;
1352  0 ps = connection.prepareStatement(sqlQuery);
1353  0 ps.setString(1, applicationName);
1354  0 ps.setInt(2, tenantId);
1355  0 ps.setString(3, groupingId);
1356  0 ps.setString(4, subscriber.getName());
1357    }
1358    } else {
1359  828 if (forceCaseInsensitiveComparisons) {
1360  828 sqlQuery += whereClauseCaseSensitive;
1361    } else {
1362  0 sqlQuery += whereClauseWithUserId;
1363    }
1364  828 ps = connection.prepareStatement(sqlQuery);
1365  828 ps.setString(1, applicationName);
1366  828 ps.setInt(2, tenantId);
1367  828 ps.setString(3, subscriber.getName());
1368    }
1369  828 result = ps.executeQuery();
1370   
1371  1656 while (result.next()) {
1372  828 subscriptionCount = result.getInt("SUB_COUNT");
1373    }
1374    } catch (SQLException e) {
1375  0 handleException("Failed to get SubscribedAPI of :" + subscriber.getName(), e);
1376    } finally {
1377  828 APIMgtDBUtil.closeAllConnections(ps, connection, result);
1378    }
1379  828 return subscriptionCount;
1380    }
1381   
1382   
1383    /**
1384    * Gets the subscribed API's, by the group for the application.
1385    *
1386    * @param subscriber the subscriber subscribing for the api
1387    * @param applicationName the application to which the api's are subscribed
1388    * @param startSubIndex the start index for pagination
1389    * @param endSubIndex end index for pagination
1390    * @param groupingId the group id of the application
1391    * @return the set of subscribed API's.
1392    * @throws APIManagementException
1393    */
 
1394  230 toggle public Set<SubscribedAPI> getPaginatedSubscribedAPIs(Subscriber subscriber, String applicationName,
1395    int startSubIndex, int endSubIndex, String groupingId)
1396    throws APIManagementException {
1397  230 Set<SubscribedAPI> subscribedAPIs = new LinkedHashSet<SubscribedAPI>();
1398  230 Connection connection = null;
1399  230 PreparedStatement ps = null;
1400  230 ResultSet result = null;
1401   
1402  230 String sqlQuery = SQLConstants.GET_PAGINATED_SUBSCRIBED_APIS_SQL;
1403   
1404  230 String whereClause = " AND SUB.USER_ID = ? ";
1405  230 String whereClauseForceCaseInsensitiveComp = " AND LOWER(SUB.USER_ID) = LOWER(?) ";
1406  230 String whereClauseWithGroupId = " AND (APP.GROUP_ID = ? OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL)"
1407    + " AND SUB.USER_ID = ?))";
1408  230 String whereClauseWithGroupIdorceCaseInsensitiveComp = " AND (APP.GROUP_ID = ?"
1409    + " OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL) AND LOWER(SUB.USER_ID) = LOWER(?)))";
1410   
1411  230 String whereClauseWithMultiGroupId = " AND ( (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM " +
1412    "AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?)) OR ( SUB.USER_ID = ? ))";
1413  230 String whereClauseWithMultiGroupIdCaseInsensitive = " AND ( (APP.APPLICATION_ID IN (SELECT APPLICATION_ID " +
1414    "FROM AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?)) OR ( LOWER(SUB.USER_ID) = LOWER" +
1415    "(?) ))";
1416  230 try {
1417  230 connection = APIMgtDBUtil.getConnection();
1418  230 int tenantId = APIUtil.getTenantId(subscriber.getName());
1419  230 if (groupingId != null && !"null".equals(groupingId) && !groupingId.isEmpty()) {
1420  0 if (multiGroupAppSharingEnabled) {
1421  0 String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
1422  0 if (forceCaseInsensitiveComparisons) {
1423  0 sqlQuery += whereClauseWithMultiGroupIdCaseInsensitive;
1424    } else {
1425  0 sqlQuery += whereClauseWithMultiGroupId;
1426    }
1427  0 String groupIDArray[] = groupingId.split(",");
1428   
1429  0 ps = fillQueryParams(connection, sqlQuery, groupIDArray, 3);
1430  0 ps.setInt(1, tenantId);
1431  0 ps.setString(2, applicationName);
1432    // dynamically seeting the parameter index
1433  0 int paramIndex = groupIDArray.length + 2;
1434  0 ps.setString(++paramIndex, tenantDomain);
1435  0 ps.setString(++paramIndex, subscriber.getName());
1436    } else {
1437  0 if (forceCaseInsensitiveComparisons) {
1438  0 sqlQuery += whereClauseWithGroupIdorceCaseInsensitiveComp;
1439    } else {
1440  0 sqlQuery += whereClauseWithGroupId;
1441    }
1442  0 ps = connection.prepareStatement(sqlQuery);
1443  0 ps.setInt(1, tenantId);
1444  0 ps.setString(2, applicationName);
1445  0 ps.setString(3, groupingId);
1446  0 ps.setString(4, subscriber.getName());
1447    }
1448   
1449    } else {
1450  230 if (forceCaseInsensitiveComparisons) {
1451  230 sqlQuery += whereClauseForceCaseInsensitiveComp;
1452    } else {
1453  0 sqlQuery += whereClause;
1454    }
1455   
1456  230 ps = connection.prepareStatement(sqlQuery);
1457  230 ps.setInt(1, tenantId);
1458  230 ps.setString(2, applicationName);
1459  230 ps.setString(3, subscriber.getName());
1460    }
1461  230 result = ps.executeQuery();
1462   
1463  230 int index = 0;
1464  286 while (result.next()) {
1465  56 if (index >= startSubIndex && index < endSubIndex) {
1466  56 APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(result.getString
1467    ("API_PROVIDER")), result.getString("API_NAME"), result.getString("API_VERSION"));
1468   
1469  56 SubscribedAPI subscribedAPI = new SubscribedAPI(subscriber, apiIdentifier);
1470  56 subscribedAPI.setSubStatus(result.getString("SUB_STATUS"));
1471  56 subscribedAPI.setSubCreatedStatus(result.getString("SUBS_CREATE_STATE"));
1472  56 subscribedAPI.setTier(new Tier(result.getString(APIConstants.SUBSCRIPTION_FIELD_TIER_ID)));
1473   
1474  56 Application application = new Application(result.getString("APP_NAME"), subscriber);
1475  56 subscribedAPI.setApplication(application);
1476  56 subscribedAPIs.add(subscribedAPI);
1477  56 if (index == endSubIndex - 1) {
1478  0 break;
1479    }
1480    }
1481  56 index++;
1482    }
1483    } catch (SQLException e) {
1484  0 handleException("Failed to get SubscribedAPI of :" + subscriber.getName(), e);
1485    } finally {
1486  230 APIMgtDBUtil.closeAllConnections(ps, connection, result);
1487    }
1488  230 return subscribedAPIs;
1489    }
1490   
1491    /**
1492    * This method returns the set of APIs for given subscriber
1493    *
1494    * @param subscriber subscriber
1495    * @return Set<API>
1496    * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to get SubscribedAPIs
1497    */
 
1498  6 toggle public Set<SubscribedAPI> getSubscribedAPIs(Subscriber subscriber, String groupingId)
1499    throws APIManagementException {
1500  6 Set<SubscribedAPI> subscribedAPIs = new LinkedHashSet<SubscribedAPI>();
1501  6 Connection connection = null;
1502  6 PreparedStatement ps = null;
1503  6 ResultSet result = null;
1504   
1505    //identify subscribeduser used email/ordinalusername
1506  6 String subscribedUserName = getLoginUserName(subscriber.getName());
1507  6 subscriber.setName(subscribedUserName);
1508   
1509  6 String sqlQuery = SQLConstants.GET_SUBSCRIBED_APIS_OF_SUBSCRIBER_SQL;
1510  6 String whereClause = " AND SUB.USER_ID = ? ";
1511  6 String whereClauseCaseInSensitive = " AND LOWER(SUB.USER_ID) = LOWER(?) ";
1512  6 String whereClauseWithGroupId = " AND (APP.GROUP_ID = ? OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL)"
1513    + " AND SUB.USER_ID = ?))";
1514  6 String whereClauseWithGroupIdorceCaseInsensitiveComp = " AND (APP.GROUP_ID = ? "
1515    + "OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL) AND LOWER(SUB.USER_ID) = LOWER(?)))";
1516   
1517  6 String whereClauseWithMultiGroupId = " AND ( (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM " +
1518    "AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?)) OR ( SUB.USER_ID = ? ))";
1519  6 String whereClauseWithMultiGroupIdCaseInsensitiveComp = " AND ( (APP.APPLICATION_ID IN (SELECT " +
1520    "APPLICATION_ID FROM " +
1521    "AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?)) OR ( LOWER(SUB.USER_ID) = LOWER(?) ))";
1522  6 try {
1523  6 connection = APIMgtDBUtil.getConnection();
1524   
1525  6 if (groupingId != null && !"null".equals(groupingId) && !groupingId.isEmpty()) {
1526   
1527  0 if (multiGroupAppSharingEnabled) {
1528  0 if (forceCaseInsensitiveComparisons) {
1529  0 sqlQuery += whereClauseWithMultiGroupIdCaseInsensitiveComp;
1530    } else {
1531  0 sqlQuery += whereClauseWithMultiGroupId;
1532    }
1533  0 String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
1534  0 String[] groupIdArr = groupingId.split(",");
1535   
1536  0 ps = fillQueryParams(connection, sqlQuery, groupIdArr, 2);
1537  0 int tenantId = APIUtil.getTenantId(subscriber.getName());
1538  0 ps.setInt(1, tenantId);
1539  0 int paramIndex = groupIdArr.length + 1;
1540  0 ps.setString(++paramIndex, tenantDomain);
1541  0 ps.setString(++paramIndex, subscriber.getName());
1542    } else {
1543  0 if (forceCaseInsensitiveComparisons) {
1544  0 sqlQuery += whereClauseWithGroupIdorceCaseInsensitiveComp;
1545    } else {
1546  0 sqlQuery += whereClauseWithGroupId;
1547    }
1548  0 ps = connection.prepareStatement(sqlQuery);
1549  0 int tenantId = APIUtil.getTenantId(subscriber.getName());
1550  0 ps.setInt(1, tenantId);
1551  0 ps.setString(2, groupingId);
1552  0 ps.setString(3, subscriber.getName());
1553    }
1554    } else {
1555  6 if (forceCaseInsensitiveComparisons) {
1556  6 sqlQuery += whereClauseCaseInSensitive;
1557    } else {
1558  0 sqlQuery += whereClause;
1559    }
1560  6 ps = connection.prepareStatement(sqlQuery);
1561  6 int tenantId = APIUtil.getTenantId(subscriber.getName());
1562  6 ps.setInt(1, tenantId);
1563  6 ps.setString(2, subscriber.getName());
1564    }
1565   
1566  6 result = ps.executeQuery();
1567   
1568  6 Map<String, Set<SubscribedAPI>> map = new TreeMap<String, Set<SubscribedAPI>>();
1569  6 LRUCache<Integer, Application> applicationCache = new LRUCache<Integer, Application>(100);
1570   
1571  10 while (result.next()) {
1572  4 APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(result.getString
1573    ("API_PROVIDER")), result.getString("API_NAME"), result.getString("API_VERSION"));
1574   
1575  4 SubscribedAPI subscribedAPI = new SubscribedAPI(subscriber, apiIdentifier);
1576  4 subscribedAPI.setSubscriptionId(result.getInt("SUBS_ID"));
1577  4 subscribedAPI.setSubStatus(result.getString("SUB_STATUS"));
1578  4 subscribedAPI.setSubCreatedStatus(result.getString("SUBS_CREATE_STATE"));
1579  4 String tierName = result.getString(APIConstants.SUBSCRIPTION_FIELD_TIER_ID);
1580  4 subscribedAPI.setTier(new Tier(tierName));
1581  4 subscribedAPI.setUUID(result.getString("SUB_UUID"));
1582    //setting NULL for subscriber. If needed, Subscriber object should be constructed &
1583    // passed in
1584  4 int applicationId = result.getInt("APP_ID");
1585  4 Application application = applicationCache.get(applicationId);
1586  4 if (application == null) {
1587  4 application = new Application(result.getString("APP_NAME"), subscriber);
1588  4 application.setId(result.getInt("APP_ID"));
1589  4 application.setTokenType(result.getString("APP_TOKEN_TYPE"));
1590  4 application.setCallbackUrl(result.getString("CALLBACK_URL"));
1591  4 application.setUUID(result.getString("APP_UUID"));
1592   
1593  4 if (multiGroupAppSharingEnabled) {
1594  0 application.setGroupId(getGroupId(application.getId()));
1595  0 application.setOwner(result.getString("OWNER"));
1596    }
1597   
1598  4 applicationCache.put(applicationId, application);
1599    }
1600  4 subscribedAPI.setApplication(application);
1601   
1602  4 if (!map.containsKey(application.getName())) {
1603  4 map.put(application.getName(), new TreeSet<>(new Comparator<SubscribedAPI>() {
 
1604  4 toggle public int compare(SubscribedAPI o1, SubscribedAPI o2) {
1605  4 int placement = o1.getApiId().getApiName().compareTo(o2.getApiId().getApiName());
1606  4 if (placement == 0) {
1607  4 return new APIVersionComparator().compare(new API(o1.getApiId()), new API(o2.getApiId
1608    ()));
1609    }
1610  0 return placement;
1611    }
1612    }));
1613    }
1614  4 map.get(application.getName()).add(subscribedAPI);
1615    }
1616   
1617  6 for (Map.Entry<String, Set<SubscribedAPI>> entry : map.entrySet()) {
1618  4 subscribedAPIs.addAll(entry.getValue());
1619    }
1620    } catch (SQLException e) {
1621  0 handleException("Failed to get SubscribedAPI of :" + subscriber.getName(), e);
1622    } finally {
1623  6 APIMgtDBUtil.closeAllConnections(ps, connection, result);
1624    }
1625  6 return subscribedAPIs;
1626    }
1627   
 
1628  0 toggle public boolean isAccessTokenExists(String accessToken) throws APIManagementException {
1629  0 Connection connection = null;
1630  0 PreparedStatement ps = null;
1631  0 ResultSet result = null;
1632   
1633  0 String accessTokenStoreTable = APIConstants.ACCESS_TOKEN_STORE_TABLE;
1634  0 accessTokenStoreTable = getAccessTokenStoreTableFromAccessToken(accessToken, accessTokenStoreTable);
1635   
1636  0 String getTokenSql = SQLConstants.IS_ACCESS_TOKEN_EXISTS_PREFIX + accessTokenStoreTable +
1637    SQLConstants.IS_ACCESS_TOKEN_EXISTS_SUFFIX;
1638  0 boolean tokenExists = false;
1639  0 try {
1640  0 connection = APIMgtDBUtil.getConnection();
1641  0 ps = connection.prepareStatement(getTokenSql);
1642  0 String encryptedAccessToken = APIUtil.encryptToken(accessToken);
1643  0 ps.setString(1, encryptedAccessToken);
1644  0 result = ps.executeQuery();
1645  0 while (result.next()) {
1646  0 tokenExists = true;
1647    }
1648    } catch (SQLException e) {
1649  0 handleException("Failed to check availability of the access token. ", e);
1650    } catch (CryptoException e) {
1651  0 handleException("Failed to check availability of the access token. ", e);
1652    } finally {
1653  0 APIMgtDBUtil.closeAllConnections(ps, connection, result);
1654    }
1655  0 return tokenExists;
1656    }
1657   
 
1658  0 toggle public boolean isAccessTokenRevoked(String accessToken) throws APIManagementException {
1659  0 Connection connection = null;
1660  0 PreparedStatement ps = null;
1661  0 ResultSet result = null;
1662   
1663  0 String accessTokenStoreTable = APIConstants.ACCESS_TOKEN_STORE_TABLE;
1664  0 accessTokenStoreTable = getAccessTokenStoreTableFromAccessToken(accessToken, accessTokenStoreTable);
1665   
1666  0 String getTokenSql = SQLConstants.IS_ACCESS_TOKEN_REVOKED_PREFIX + accessTokenStoreTable +
1667    SQLConstants.IS_ACCESS_TOKE_REVOKED_SUFFIX;
1668  0 boolean tokenExists = false;
1669  0 try {
1670  0 connection = APIMgtDBUtil.getConnection();
1671  0 ps = connection.prepareStatement(getTokenSql);
1672  0 String encryptedAccessToken = APIUtil.encryptToken(accessToken);
1673  0 ps.setString(1, encryptedAccessToken);
1674  0 result = ps.executeQuery();
1675  0 while (result.next()) {
1676  0 if (!"REVOKED".equals(result.getString("TOKEN_STATE"))) {
1677  0 tokenExists = true;
1678    }
1679    }
1680    } catch (SQLException e) {
1681  0 handleException("Failed to check availability of the access token. ", e);
1682    } catch (CryptoException e) {
1683  0 handleException("Failed to check availability of the access token. ", e);
1684    } finally {
1685  0 APIMgtDBUtil.closeAllConnections(ps, connection, result);
1686    }
1687  0 return tokenExists;
1688    }
1689   
 
1690  0 toggle public APIKey getAccessTokenData(String accessToken) throws APIManagementException {
1691  0 Connection connection = null;
1692  0 PreparedStatement ps = null;
1693  0 ResultSet result = null;
1694  0 APIKey apiKey = new APIKey();
1695   
1696  0 String accessTokenStoreTable = APIConstants.ACCESS_TOKEN_STORE_TABLE;
1697  0 accessTokenStoreTable = getAccessTokenStoreTableFromAccessToken(accessToken, accessTokenStoreTable);
1698   
1699  0 String getTokenSql = SQLConstants.GET_ACCESS_TOKEN_DATA_PREFIX + accessTokenStoreTable + SQLConstants
1700    .GET_ACCESS_TOKEN_DATA_SUFFIX;
1701  0 try {
1702  0 connection = APIMgtDBUtil.getConnection();
1703  0 ps = connection.prepareStatement(getTokenSql);
1704  0 ps.setString(1, APIUtil.encryptToken(accessToken));
1705  0 result = ps.executeQuery();
1706  0 if (result.next()) {
1707  0 String decryptedAccessToken = APIUtil.decryptToken(result.getString("ACCESS_TOKEN")); // todo - check
1708   
1709  0 String endUserName = result.getString(APIConstants.IDENTITY_OAUTH2_FIELD_AUTHORIZED_USER);
1710  0 String domainName = result.getString(APIConstants.IDENTITY_OAUTH2_FIELD_USER_DOMAIN);
1711  0 String endUsernameWithDomain = UserCoreUtil.addDomainToName(endUserName, domainName);
1712  0 apiKey.setAuthUser(endUsernameWithDomain);
1713   
1714  0 apiKey.setAccessToken(decryptedAccessToken);
1715  0 apiKey.setCreatedDate(result.getTimestamp("TIME_CREATED").toString().split("\\.")[0]);
1716  0 String consumerKey = result.getString("CONSUMER_KEY");
1717  0 apiKey.setConsumerKey(consumerKey);
1718  0 apiKey.setValidityPeriod(result.getLong("VALIDITY_PERIOD"));
1719  0 List<String> scopes = new ArrayList<String>();
1720  0 do {
1721  0 scopes.add(result.getString(APIConstants.IDENTITY_OAUTH2_FIELD_TOKEN_SCOPE));
1722  0 } while (result.next());
1723  0 apiKey.setTokenScope(getScopeString(scopes));
1724    }
1725    } catch (SQLException e) {
1726  0 handleException("Failed to get the access token data. ", e);
1727    } catch (CryptoException e) {
1728  0 handleException("Failed to get the access token data. ", e);
1729    } finally {
1730  0 APIMgtDBUtil.closeAllConnections(ps, connection, result);
1731    }
1732  0 return apiKey;
1733    }
1734   
 
1735  0 toggle public Map<Integer, APIKey> getAccessTokens(String query) throws APIManagementException {
1736  0 Map<Integer, APIKey> tokenDataMap = new HashMap<Integer, APIKey>();
1737  0 if (APIUtil.checkAccessTokenPartitioningEnabled() && APIUtil.checkUserNameAssertionEnabled()) {
1738  0 String[] keyStoreTables = APIUtil.getAvailableKeyStoreTables();
1739  0 if (keyStoreTables != null) {
1740  0 for (String keyStoreTable : keyStoreTables) {
1741  0 Map<Integer, APIKey> tokenDataMapTmp = getAccessTokens(query, getTokenSql(keyStoreTable));
1742  0 tokenDataMap.putAll(tokenDataMapTmp);
1743    }
1744    }
1745    } else {
1746  0 tokenDataMap = getAccessTokens(query, getTokenSql(null));
1747    }
1748  0 return tokenDataMap;
1749    }
1750   
 
1751  0 toggle private Map<Integer, APIKey> getAccessTokens(String query, String getTokenSql) throws APIManagementException {
1752  0 Connection connection = null;
1753  0 PreparedStatement ps = null;
1754  0 ResultSet result = null;
1755  0 Map<Integer, APIKey> tokenDataMap = new HashMap<Integer, APIKey>();
1756   
1757  0 try {
1758  0 connection = APIMgtDBUtil.getConnection();
1759  0 ps = connection.prepareStatement(getTokenSql);
1760  0 result = ps.executeQuery();
1761  0 boolean accessTokenRowBreaker = false;
1762   
1763  0 Integer i = 0;
1764  0 while (accessTokenRowBreaker || result.next()) {
1765  0 accessTokenRowBreaker = false;
1766  0 String accessToken = APIUtil.decryptToken(result.getString("ACCESS_TOKEN"));
1767  0 String regex = "(?i)[a-zA-Z0-9_.-|]*" + query.trim() + "(?i)[a-zA-Z0-9_.-|]*";
1768  0 Pattern pattern;
1769  0 Matcher matcher;
1770  0 pattern = Pattern.compile(regex);
1771  0 matcher = pattern.matcher(accessToken);
1772  0 if (matcher.matches()) {
1773  0 APIKey apiKey = new APIKey();
1774  0 apiKey.setAccessToken(accessToken);
1775   
1776  0 String username = result.getString(APIConstants.IDENTITY_OAUTH2_FIELD_AUTHORIZED_USER);
1777  0 String domainName = result.getString(APIConstants.IDENTITY_OAUTH2_FIELD_USER_DOMAIN);
1778  0 String endUsernameWithDomain = UserCoreUtil.addDomainToName(username, domainName);
1779  0 apiKey.setAuthUser(endUsernameWithDomain);
1780   
1781  0 apiKey.setCreatedDate(result.getTimestamp("TIME_CREATED").toString().split("\\.")[0]);
1782  0 String consumerKey = result.getString("CONSUMER_KEY");
1783  0 apiKey.setConsumerKey(consumerKey);
1784  0 apiKey.setValidityPeriod(result.getLong("VALIDITY_PERIOD"));
1785    // Load all the rows to in memory and build the scope string
1786  0 List<String> scopes = new ArrayList<String>();
1787  0 String tokenString = result.getString("ACCESS_TOKEN");
1788  0 do {
1789  0 String currentRowTokenString = result.getString("ACCESS_TOKEN");
1790  0 if (tokenString.equals(currentRowTokenString)) {
1791  0 scopes.add(result.getString(APIConstants.IDENTITY_OAUTH2_FIELD_TOKEN_SCOPE));
1792    } else {
1793  0 accessTokenRowBreaker = true;
1794  0 break;
1795    }
1796  0 } while (result.next());
1797  0 apiKey.setTokenScope(getScopeString(scopes));
1798  0 tokenDataMap.put(i, apiKey);
1799  0 i++;
1800    }
1801    }
1802    } catch (SQLException e) {
1803  0 handleException("Failed to get access token data. ", e);
1804    } catch (CryptoException e) {
1805  0 handleException("Failed to get access token data. ", e);
1806    } finally {
1807  0 APIMgtDBUtil.closeAllConnections(ps, connection, result);
1808    }
1809  0 return tokenDataMap;
1810    }
1811   
 
1812  0 toggle private String getTokenSql(String accessTokenStoreTable) {
1813  0 String tokenStoreTable = APIConstants.ACCESS_TOKEN_STORE_TABLE;
1814  0 if (accessTokenStoreTable != null) {
1815  0 tokenStoreTable = accessTokenStoreTable;
1816    }
1817  0 return SQLConstants.GET_TOKEN_SQL_PREFIX + tokenStoreTable + SQLConstants.GET_TOKEN_SQL_SUFFIX;
1818    }
1819   
 
1820  0 toggle public Map<Integer, APIKey> getAccessTokensByUser(String user, String loggedInUser) throws APIManagementException {
1821  0 Connection connection = null;
1822  0 PreparedStatement ps = null;
1823  0 ResultSet result = null;
1824  0 Map<Integer, APIKey> tokenDataMap = new HashMap<Integer, APIKey>();
1825   
1826  0 String accessTokenStoreTable = APIConstants.ACCESS_TOKEN_STORE_TABLE;
1827  0 accessTokenStoreTable = getAccessTokenStoreTableNameOfUserId(user, accessTokenStoreTable);
1828   
1829  0 String getTokenSql = SQLConstants.GET_ACCESS_TOKEN_BY_USER_PREFIX + accessTokenStoreTable + SQLConstants
1830    .GET_ACCESS_TOKEN_BY_USER_SUFFIX;
1831  0 try {
1832  0 connection = APIMgtDBUtil.getConnection();
1833  0 ps = connection.prepareStatement(getTokenSql);
1834  0 ps.setString(1, user);
1835  0 result = ps.executeQuery();
1836  0 Integer i = 0;
1837  0 boolean accessTokenRowBreaker = false;
1838  0 while (accessTokenRowBreaker || result.next()) {
1839  0 accessTokenRowBreaker = false;
1840  0 String username = result.getString(APIConstants.IDENTITY_OAUTH2_FIELD_AUTHORIZED_USER);
1841  0 String domainName = result.getString(APIConstants.IDENTITY_OAUTH2_FIELD_USER_DOMAIN);
1842  0 String authorizedUserWithDomain = UserCoreUtil.addDomainToName(username, domainName);
1843   
1844  0 if (APIUtil.isLoggedInUserAuthorizedToRevokeToken(loggedInUser, authorizedUserWithDomain)) {
1845  0 String accessToken = APIUtil.decryptToken(result.getString("ACCESS_TOKEN"));
1846  0 APIKey apiKey = new APIKey();
1847  0 apiKey.setAccessToken(accessToken);
1848  0 apiKey.setAuthUser(authorizedUserWithDomain);
1849  0 apiKey.setCreatedDate(result.getTimestamp("TIME_CREATED").toString().split("\\.")[0]);
1850  0 String consumerKey = result.getString("CONSUMER_KEY");
1851  0 apiKey.setConsumerKey(consumerKey);
1852  0 apiKey.setValidityPeriod(result.getLong("VALIDITY_PERIOD"));
1853    // Load all the rows to in memory and build the scope string
1854  0 List<String> scopes = new ArrayList<String>();
1855  0 String tokenString = result.getString("ACCESS_TOKEN");
1856  0 do {
1857  0 String currentRowTokenString = result.getString("ACCESS_TOKEN");
1858  0 if (tokenString.equals(currentRowTokenString)) {
1859  0 scopes.add(result.getString(APIConstants.IDENTITY_OAUTH2_FIELD_TOKEN_SCOPE));
1860    } else {
1861  0 accessTokenRowBreaker = true;
1862  0 break;
1863    }
1864  0 } while (result.next());
1865  0 apiKey.setTokenScope(getScopeString(scopes));
1866  0 tokenDataMap.put(i, apiKey);
1867  0 i++;
1868    }
1869    }
1870    } catch (SQLException e) {
1871  0 handleException("Failed to get access token data. ", e);
1872    } catch (CryptoException e) {
1873  0 handleException("Failed to get access token data. ", e);
1874    } finally {
1875  0 APIMgtDBUtil.closeAllConnections(ps, connection, result);
1876    }
1877  0 return tokenDataMap;
1878    }
1879   
1880   
 
1881  377 toggle private Map<String, OAuthApplicationInfo> getOAuthApplications(int applicationId) throws APIManagementException {
1882  377 Map<String, OAuthApplicationInfo> map = new HashMap<String, OAuthApplicationInfo>();
1883  377 OAuthApplicationInfo prodApp = getClientOfApplication(applicationId, "PRODUCTION");
1884  377 if (prodApp != null) {
1885  274 map.put("PRODUCTION", prodApp);
1886    }
1887   
1888  377 OAuthApplicationInfo sandboxApp = getClientOfApplication(applicationId, "SANDBOX");
1889  377 if (sandboxApp != null) {
1890  11 map.put("SANDBOX", sandboxApp);
1891    }
1892   
1893  377 return map;
1894    }
1895   
 
1896  754 toggle public OAuthApplicationInfo getClientOfApplication(int applicationID, String keyType)
1897    throws APIManagementException {
1898  754 String sqlQuery = SQLConstants.GET_CLIENT_OF_APPLICATION_SQL;
1899   
1900  754 KeyManager keyManager = null;
1901  754 OAuthApplicationInfo oAuthApplication = null;
1902  754 Connection connection = null;
1903  754 PreparedStatement ps = null;
1904  754 ResultSet rs = null;
1905  754 String consumerKey = null;
1906  754 try {
1907  754 connection = APIMgtDBUtil.getConnection();
1908  754 ps = connection.prepareStatement(sqlQuery);
1909  754 ps.setInt(1, applicationID);
1910  754 ps.setString(2, keyType);
1911  754 rs = ps.executeQuery();
1912   
1913  1039 while (rs.next()) {
1914  285 consumerKey = rs.getString(1);
1915    }
1916   
1917  754 if (consumerKey != null) {
1918  285 keyManager = KeyManagerHolder.getKeyManagerInstance();
1919  285 oAuthApplication = keyManager.retrieveApplication(consumerKey);
1920    }
1921    } catch (SQLException e) {
1922  0 handleException("Failed to get client of application. SQL error", e);
1923    } finally {
1924  754 APIMgtDBUtil.closeAllConnections(ps, connection, rs);
1925    }
1926   
1927  754 return oAuthApplication;
1928    }
1929   
 
1930  866 toggle public APIKey getKeyStatusOfApplication(String keyType, int applicationId) throws APIManagementException {
1931  866 Connection connection = null;
1932  866 PreparedStatement preparedStatement = null;
1933  866 ResultSet resultSet = null;
1934  866 APIKey key = null;
1935   
1936  866 String sqlQuery = SQLConstants.GET_KEY_STATUS_OF_APPLICATION_SQL;
1937  866 try {
1938  866 connection = APIMgtDBUtil.getConnection();
1939  866 preparedStatement = connection.prepareStatement(sqlQuery);
1940  866 preparedStatement.setInt(1, applicationId);
1941  866 preparedStatement.setString(2, keyType);
1942   
1943  866 resultSet = preparedStatement.executeQuery();
1944  1166 while (resultSet.next()) {
1945  300 key = new APIKey();
1946  300 key.setState(resultSet.getString("STATE"));
1947    }
1948    } catch (SQLException e) {
1949  0 handleException("Error occurred while getting the State of Access Token", e);
1950    } finally {
1951  866 APIMgtDBUtil.closeAllConnections(preparedStatement, connection, resultSet);
1952    }
1953  866 return key;
1954    }
1955   
1956    /**
1957    * Gets ConsumerKeys when given the Application ID.
1958    *
1959    * @param applicationId
1960    * @return {@link java.util.Set} containing ConsumerKeys
1961    * @throws APIManagementException
1962    */
 
1963  322 toggle public Set<String> getConsumerKeysOfApplication(int applicationId) throws APIManagementException {
1964  322 Connection connection = null;
1965  322 PreparedStatement preparedStatement = null;
1966  322 ResultSet resultSet = null;
1967  322 Set<String> consumerKeys = new HashSet<String>();
1968   
1969  322 String sqlQuery = SQLConstants.GET_CONSUMER_KEYS_OF_APPLICATION_SQL;
1970  322 try {
1971  322 connection = APIMgtDBUtil.getConnection();
1972  322 preparedStatement = connection.prepareStatement(sqlQuery);
1973  322 preparedStatement.setInt(1, applicationId);
1974  322 resultSet = preparedStatement.executeQuery();
1975  485 while (resultSet.next()) {
1976  163 String consumerKey = resultSet.getString("CONSUMER_KEY");
1977  163 if (consumerKey != null) {
1978  163 consumerKeys.add(consumerKey);
1979    }
1980    }
1981    } catch (SQLException e) {
1982  0 handleException("Error occurred while getting the State of Access Token", e);
1983    } finally {
1984  322 APIMgtDBUtil.closeAllConnections(preparedStatement, connection, resultSet);
1985    }
1986   
1987  322 return consumerKeys;
1988    }
1989   
 
1990  0 toggle public Set<String> getApplicationKeys(int applicationId) throws APIManagementException {
1991  0 Set<String> apiKeys = new HashSet<String>();
1992  0 if (APIUtil.checkAccessTokenPartitioningEnabled() && APIUtil.checkUserNameAssertionEnabled()) {
1993  0 String[] keyStoreTables = APIUtil.getAvailableKeyStoreTables();
1994  0 if (keyStoreTables != null) {
1995  0 for (String keyStoreTable : keyStoreTables) {
1996  0 apiKeys = getApplicationKeys(applicationId, getKeysSql(keyStoreTable));
1997  0 if (apiKeys.size() > 0) {
1998  0 break;
1999    }
2000    }
2001    }
2002    } else {
2003  0 apiKeys = getApplicationKeys(applicationId, getKeysSql(null));
2004    }
2005  0 return apiKeys;
2006    }
2007   
 
2008  6 toggle public void updateTierPermissions(String tierName, String permissionType, String roles, int tenantId)
2009    throws APIManagementException {
2010  6 Connection conn = null;
2011  6 PreparedStatement ps = null;
2012  6 PreparedStatement insertOrUpdatePS = null;
2013  6 ResultSet resultSet = null;
2014  6 int tierPermissionId = -1;
2015   
2016  6 try {
2017  6 conn = APIMgtDBUtil.getConnection();
2018  6 conn.setAutoCommit(false);
2019   
2020  6 String getTierPermissionQuery = SQLConstants.GET_TIER_PERMISSION_ID_SQL;
2021  6 ps = conn.prepareStatement(getTierPermissionQuery);
2022  6 ps.setString(1, tierName);
2023  6 ps.setInt(2, tenantId);
2024  6 resultSet = ps.executeQuery();
2025  6 if (resultSet.next()) {
2026  4 tierPermissionId = resultSet.getInt("TIER_PERMISSIONS_ID");
2027    }
2028   
2029  6 if (tierPermissionId == -1) {
2030  2 String query = SQLConstants.ADD_TIER_PERMISSION_SQL;
2031  2 insertOrUpdatePS = conn.prepareStatement(query);
2032  2 insertOrUpdatePS.setString(1, tierName);
2033  2 insertOrUpdatePS.setString(2, permissionType);
2034  2 insertOrUpdatePS.setString(3, roles);
2035  2 insertOrUpdatePS.setInt(4, tenantId);
2036  2 insertOrUpdatePS.execute();
2037    } else {
2038  4 String query = SQLConstants.UPDATE_TIER_PERMISSION_SQL;
2039  4 insertOrUpdatePS = conn.prepareStatement(query);
2040  4 insertOrUpdatePS.setString(1, tierName);
2041  4 insertOrUpdatePS.setString(2, permissionType);
2042  4 insertOrUpdatePS.setString(3, roles);
2043  4 insertOrUpdatePS.setInt(4, tierPermissionId);
2044  4 insertOrUpdatePS.setInt(5, tenantId);
2045  4 insertOrUpdatePS.executeUpdate();
2046    }
2047  6 conn.commit();
2048    } catch (SQLException e) {
2049  0 handleException("Error in updating tier permissions: " + e.getMessage(), e);
2050    } finally {
2051  6 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
2052  6 APIMgtDBUtil.closeAllConnections(insertOrUpdatePS, null, null);
2053    }
2054    }
2055   
 
2056  4 toggle public Set<TierPermissionDTO> getTierPermissions(int tenantId) throws APIManagementException {
2057  4 Connection conn = null;
2058  4 PreparedStatement ps = null;
2059  4 ResultSet resultSet = null;
2060   
2061  4 Set<TierPermissionDTO> tierPermissions = new HashSet<TierPermissionDTO>();
2062   
2063  4 try {
2064  4 String getTierPermissionQuery = SQLConstants.GET_TIER_PERMISSIONS_SQL;
2065   
2066  4 conn = APIMgtDBUtil.getConnection();
2067  4 ps = conn.prepareStatement(getTierPermissionQuery);
2068  4 ps.setInt(1, tenantId);
2069   
2070  4 resultSet = ps.executeQuery();
2071  7 while (resultSet.next()) {
2072  3 TierPermissionDTO tierPermission = new TierPermissionDTO();
2073  3 tierPermission.setTierName(resultSet.getString("TIER"));
2074  3 tierPermission.setPermissionType(resultSet.getString("PERMISSIONS_TYPE"));
2075  3 String roles = resultSet.getString("ROLES");
2076  3 if (roles != null && !roles.isEmpty()) {
2077  3 String roleList[] = roles.split(",");
2078  3 tierPermission.setRoles(roleList);
2079    }
2080  3 tierPermissions.add(tierPermission);
2081    }
2082    } catch (SQLException e) {
2083  0 handleException("Failed to get Tier permission information ", e);
2084    } finally {
2085  4 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
2086    }
2087  4 return tierPermissions;
2088    }
2089   
 
2090  7 toggle public TierPermissionDTO getTierPermission(String tierName, int tenantId) throws APIManagementException {
2091  7 Connection conn = null;
2092  7 PreparedStatement ps = null;
2093  7 ResultSet resultSet = null;
2094   
2095  7 TierPermissionDTO tierPermission = null;
2096  7 try {
2097  7 String getTierPermissionQuery = SQLConstants.GET_PERMISSION_OF_TIER_SQL;
2098  7 conn = APIMgtDBUtil.getConnection();
2099  7 ps = conn.prepareStatement(getTierPermissionQuery);
2100   
2101  7 ps.setString(1, tierName);
2102  7 ps.setInt(2, tenantId);
2103   
2104  7 resultSet = ps.executeQuery();
2105  9 while (resultSet.next()) {
2106  2 tierPermission = new TierPermissionDTO();
2107  2 tierPermission.setTierName(tierName);
2108  2 tierPermission.setPermissionType(resultSet.getString("PERMISSIONS_TYPE"));
2109  2 String roles = resultSet.getString("ROLES");
2110  2 if (roles != null) {
2111  2 String roleList[] = roles.split(",");
2112  2 tierPermission.setRoles(roleList);
2113    }
2114    }
2115    } catch (SQLException e) {
2116  0 handleException("Failed to get Tier permission information for Tier " + tierName, e);
2117    } finally {
2118  7 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
2119    }
2120  7 return tierPermission;
2121    }
2122   
 
2123  3 toggle public TierPermissionDTO getThrottleTierPermission(String tierName, int tenantId) throws APIManagementException {
2124  3 Connection conn = null;
2125  3 PreparedStatement ps = null;
2126  3 ResultSet resultSet = null;
2127   
2128  3 TierPermissionDTO tierPermission = null;
2129  3 try {
2130  3 String getTierPermissionQuery = SQLConstants.GET_THROTTLE_TIER_PERMISSION_SQL;
2131  3 conn = APIMgtDBUtil.getConnection();
2132  3 ps = conn.prepareStatement(getTierPermissionQuery);
2133   
2134  3 ps.setString(1, tierName);
2135  3 ps.setInt(2, tenantId);
2136   
2137  3 resultSet = ps.executeQuery();
2138  3 while (resultSet.next()) {
2139  0 tierPermission = new TierPermissionDTO();
2140  0 tierPermission.setTierName(tierName);
2141  0 tierPermission.setPermissionType(resultSet.getString("PERMISSIONS_TYPE"));
2142  0 String roles = resultSet.getString("ROLES");
2143  0 if (roles != null) {
2144  0 String roleList[] = roles.split(",");
2145  0 tierPermission.setRoles(roleList);
2146    }
2147    }
2148    } catch (SQLException e) {
2149  0 handleException("Failed to get Tier permission information for Tier " + tierName, e);
2150    } finally {
2151  3 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
2152    }
2153  3 return tierPermission;
2154    }
2155   
2156   
 
2157  0 toggle public void updateThrottleTierPermissions(String tierName, String permissionType, String roles, int tenantId)
2158    throws APIManagementException {
2159  0 Connection conn = null;
2160  0 PreparedStatement ps = null;
2161  0 PreparedStatement insertOrUpdatePS = null;
2162  0 ResultSet resultSet = null;
2163  0 int tierPermissionId = -1;
2164   
2165  0 try {
2166  0 conn = APIMgtDBUtil.getConnection();
2167  0 conn.setAutoCommit(false);
2168   
2169  0 String getTierPermissionQuery = SQLConstants.GET_THROTTLE_TIER_PERMISSION_ID_SQL;
2170  0 ps = conn.prepareStatement(getTierPermissionQuery);
2171  0 ps.setString(1, tierName);
2172  0 ps.setInt(2, tenantId);
2173  0 resultSet = ps.executeQuery();
2174  0 if (resultSet.next()) {
2175  0 tierPermissionId = resultSet.getInt("THROTTLE_TIER_PERMISSIONS_ID");
2176    }
2177   
2178  0 if (tierPermissionId == -1) {
2179  0 String query = SQLConstants.ADD_THROTTLE_TIER_PERMISSION_SQL;
2180  0 insertOrUpdatePS = conn.prepareStatement(query);
2181  0 insertOrUpdatePS.setString(1, tierName);
2182  0 insertOrUpdatePS.setString(2, permissionType);
2183  0 insertOrUpdatePS.setString(3, roles);
2184  0 insertOrUpdatePS.setInt(4, tenantId);
2185  0 insertOrUpdatePS.execute();
2186    } else {
2187  0 String query = SQLConstants.UPDATE_THROTTLE_TIER_PERMISSION_SQL;
2188  0 insertOrUpdatePS = conn.prepareStatement(query);
2189  0 insertOrUpdatePS.setString(1, tierName);
2190  0 insertOrUpdatePS.setString(2, permissionType);
2191  0 insertOrUpdatePS.setString(3, roles);
2192  0 insertOrUpdatePS.setInt(4, tierPermissionId);
2193  0 insertOrUpdatePS.setInt(5, tenantId);
2194  0 insertOrUpdatePS.executeUpdate();
2195    }
2196  0 conn.commit();
2197    } catch (SQLException e) {
2198  0 handleException("Error in updating tier permissions: " + e.getMessage(), e);
2199    } finally {
2200  0 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
2201  0 APIMgtDBUtil.closeAllConnections(insertOrUpdatePS, null, null);
2202    }
2203    }
2204   
 
2205  6 toggle public Set<TierPermissionDTO> getThrottleTierPermissions(int tenantId) throws APIManagementException {
2206  6 Connection conn = null;
2207  6 PreparedStatement ps = null;
2208  6 ResultSet resultSet = null;
2209   
2210  6 Set<TierPermissionDTO> tierPermissions = new HashSet<TierPermissionDTO>();
2211   
2212  6 try {
2213  6 String getTierPermissionQuery = SQLConstants.GET_THROTTLE_TIER_PERMISSIONS_SQL;
2214   
2215  6 conn = APIMgtDBUtil.getConnection();
2216  6 ps = conn.prepareStatement(getTierPermissionQuery);
2217  6 ps.setInt(1, tenantId);
2218   
2219  6 resultSet = ps.executeQuery();
2220  6 while (resultSet.next()) {
2221  0 TierPermissionDTO tierPermission = new TierPermissionDTO();
2222  0 tierPermission.setTierName(resultSet.getString("TIER"));
2223  0 tierPermission.setPermissionType(resultSet.getString("PERMISSIONS_TYPE"));
2224  0 String roles = resultSet.getString("ROLES");
2225  0 if (roles != null && !roles.isEmpty()) {
2226  0 String roleList[] = roles.split(",");
2227  0 tierPermission.setRoles(roleList);
2228    }
2229  0 tierPermissions.add(tierPermission);
2230    }
2231    } catch (SQLException e) {
2232  0 handleException("Failed to get Tier permission information ", e);
2233    } finally {
2234  6 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
2235    }
2236  6 return tierPermissions;
2237    }
2238   
 
2239  0 toggle private Set<String> getApplicationKeys(int applicationId, String getKeysSql) throws APIManagementException {
2240  0 Connection connection = null;
2241  0 PreparedStatement ps = null;
2242  0 ResultSet result = null;
2243  0 Set<String> apiKeys = new HashSet<String>();
2244  0 try {
2245  0 connection = APIMgtDBUtil.getConnection();
2246  0 ps = connection.prepareStatement(getKeysSql);
2247  0 ps.setInt(1, applicationId);
2248  0 result = ps.executeQuery();
2249  0 while (result.next()) {
2250  0 apiKeys.add(APIUtil.decryptToken(result.getString("ACCESS_TOKEN")));
2251    }
2252    } catch (SQLException e) {
2253  0 handleException("Failed to get keys for application: " + applicationId, e);
2254    } catch (CryptoException e) {
2255  0 handleException("Failed to get keys for application: " + applicationId, e);
2256    } finally {
2257  0 APIMgtDBUtil.closeAllConnections(ps, connection, result);
2258    }
2259  0 return apiKeys;
2260    }
2261   
 
2262  0 toggle private String getKeysSql(String accessTokenStoreTable) {
2263  0 String tokenStoreTable = APIConstants.ACCESS_TOKEN_STORE_TABLE;
2264  0 if (accessTokenStoreTable != null) {
2265  0 tokenStoreTable = accessTokenStoreTable;
2266    }
2267   
2268  0 return SQLConstants.GET_KEY_SQL_PREFIX + tokenStoreTable + SQLConstants.GET_KEY_SQL_SUFFIX;
2269    }
2270   
2271    /**
2272    * Get access token data based on application ID
2273    *
2274    * @param subscriptionId Subscription Id
2275    * @return access token data
2276    * @throws APIManagementException
2277    */
 
2278  2 toggle public Map<String, String> getAccessTokenData(int subscriptionId) throws APIManagementException {
2279  2 Map<String, String> apiKeys = new HashMap<String, String>();
2280   
2281  2 if (APIUtil.checkAccessTokenPartitioningEnabled() && APIUtil.checkUserNameAssertionEnabled()) {
2282  0 String[] keyStoreTables = APIUtil.getAvailableKeyStoreTables();
2283  0 if (keyStoreTables != null) {
2284  0 for (String keyStoreTable : keyStoreTables) {
2285  0 apiKeys = getAccessTokenData(subscriptionId, getKeysSqlUsingSubscriptionId(keyStoreTable));
2286  0 if (apiKeys.size() > 0) {
2287  0 break;
2288    }
2289    }
2290    }
2291    } else {
2292  2 apiKeys = getAccessTokenData(subscriptionId, getKeysSqlUsingSubscriptionId(null));
2293    }
2294  2 return apiKeys;
2295    }
2296   
 
2297  2 toggle private Map<String, String> getAccessTokenData(int subscriptionId, String getKeysSql)
2298    throws APIManagementException {
2299  2 Connection connection = null;
2300  2 PreparedStatement ps = null;
2301  2 ResultSet result = null;
2302  2 Map<String, String> apiKeys = new HashMap<String, String>();
2303  2 try {
2304  2 connection = APIMgtDBUtil.getConnection();
2305  2 ps = connection.prepareStatement(getKeysSql);
2306  2 ps.setInt(1, subscriptionId);
2307  2 result = ps.executeQuery();
2308  2 while (result.next()) {
2309  0 apiKeys.put("token", APIUtil.decryptToken(result.getString("ACCESS_TOKEN")));
2310  0 apiKeys.put("status", result.getString("TOKEN_STATE"));
2311    }
2312    } catch (SQLException e) {
2313  0 handleException("Failed to get keys for application: " + subscriptionId, e);
2314    } catch (CryptoException e) {
2315  0 handleException("Failed to get keys for application: " + subscriptionId, e);
2316    } finally {
2317  2 APIMgtDBUtil.closeAllConnections(ps, connection, result);
2318    }
2319  2 return apiKeys;
2320    }
2321   
 
2322  2 toggle private String getKeysSqlUsingSubscriptionId(String accessTokenStoreTable) {
2323  2 String tokenStoreTable = APIConstants.ACCESS_TOKEN_STORE_TABLE;
2324  2 if (accessTokenStoreTable != null) {
2325  0 tokenStoreTable = accessTokenStoreTable;
2326    }
2327   
2328  2 return SQLConstants.GET_KEY_SQL_OF_SUBSCRIPTION_ID_PREFIX +
2329    tokenStoreTable + SQLConstants.GET_KEY_SQL_OF_SUBSCRIPTION_ID_SUFFIX;
2330    }
2331   
2332    /**
2333    * This method returns the set of Subscribers for given provider
2334    *
2335    * @param providerName name of the provider
2336    * @return Set<Subscriber>
2337    * @throws APIManagementException if failed to get subscribers for given provider
2338    */
 
2339  0 toggle public Set<Subscriber> getSubscribersOfProvider(String providerName) throws APIManagementException {
2340   
2341  0 Set<Subscriber> subscribers = new HashSet<Subscriber>();
2342  0 Connection connection = null;
2343  0 PreparedStatement ps = null;
2344  0 ResultSet result = null;
2345   
2346  0 try {
2347  0 String sqlQuery = SQLConstants.GET_SUBSCRIBERS_OF_PROVIDER_SQL;
2348  0 connection = APIMgtDBUtil.getConnection();
2349   
2350  0 ps = connection.prepareStatement(sqlQuery);
2351  0 ps.setString(1, APIUtil.replaceEmailDomainBack(providerName));
2352  0 result = ps.executeQuery();
2353   
2354  0 while (result.next()) {
2355    // Subscription table should have API_VERSION AND API_PROVIDER
2356  0 Subscriber subscriber = new Subscriber(result.getString(APIConstants.SUBSCRIBER_FIELD_EMAIL_ADDRESS));
2357  0 subscriber.setName(result.getString(APIConstants.SUBSCRIBER_FIELD_USER_ID));
2358  0 subscriber.setSubscribedDate(result.getDate(APIConstants.SUBSCRIBER_FIELD_DATE_SUBSCRIBED));
2359  0 subscribers.add(subscriber);
2360    }
2361   
2362    } catch (SQLException e) {
2363  0 handleException("Failed to subscribers for :" + providerName, e);
2364    } finally {
2365  0 APIMgtDBUtil.closeAllConnections(ps, connection, result);
2366    }
2367  0 return subscribers;
2368    }
2369   
 
2370  317 toggle public Set<Subscriber> getSubscribersOfAPI(APIIdentifier identifier) throws APIManagementException {
2371   
2372  317 Set<Subscriber> subscribers = new HashSet<Subscriber>();
2373  317 Connection connection = null;
2374  317 PreparedStatement ps = null;
2375  317 ResultSet result = null;
2376   
2377  317 try {
2378  317 String sqlQuery = SQLConstants.GET_SUBSCRIBERS_OF_API_SQL;
2379  317 connection = APIMgtDBUtil.getConnection();
2380   
2381  317 ps = connection.prepareStatement(sqlQuery);
2382  317 ps.setString(1, APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
2383  317 ps.setString(2, identifier.getApiName());
2384  317 ps.setString(3, identifier.getVersion());
2385  317 result = ps.executeQuery();
2386  359 while (result.next()) {
2387  42 Subscriber subscriber = new Subscriber(result.getString(APIConstants.SUBSCRIBER_FIELD_USER_ID));
2388  42 subscriber.setSubscribedDate(result.getTimestamp(APIConstants.SUBSCRIBER_FIELD_DATE_SUBSCRIBED));
2389  42 subscribers.add(subscriber);
2390    }
2391    } catch (SQLException e) {
2392  0 handleException("Failed to get subscribers for :" + identifier.getApiName(), e);
2393    } finally {
2394  317 APIMgtDBUtil.closeAllConnections(ps, connection, result);
2395    }
2396  317 return subscribers;
2397    }
2398   
 
2399  262 toggle public long getAPISubscriptionCountByAPI(APIIdentifier identifier) throws APIManagementException {
2400   
2401  262 String sqlQuery = SQLConstants.GET_API_SUBSCRIPTION_COUNT_BY_API_SQL;
2402  262 long subscriptions = 0;
2403   
2404  262 Connection connection = null;
2405  262 PreparedStatement ps = null;
2406  262 ResultSet result = null;
2407   
2408  262 try {
2409  262 connection = APIMgtDBUtil.getConnection();
2410   
2411  262 ps = connection.prepareStatement(sqlQuery);
2412  262 ps.setString(1, APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
2413  262 ps.setString(2, identifier.getApiName());
2414  262 ps.setString(3, identifier.getVersion());
2415  262 result = ps.executeQuery();
2416  524 while (result.next()) {
2417  262 subscriptions = result.getLong("SUB_ID");
2418    }
2419    } catch (SQLException e) {
2420  0 handleException("Failed to get subscription count for API", e);
2421    } finally {
2422  262 APIMgtDBUtil.closeAllConnections(ps, connection, result);
2423    }
2424  262 return subscriptions;
2425    }
2426   
2427    /**
2428    * This method is used to update the subscriber
2429    *
2430    * @param identifier APIIdentifier
2431    * @param context Context of the API
2432    * @param applicationId Application id
2433    * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to update subscriber
2434    */
 
2435  0 toggle public void updateSubscriptions(APIIdentifier identifier, String context, int applicationId, String subscriber)
2436    throws APIManagementException {
2437  0 addSubscription(identifier, context, applicationId, APIConstants.SubscriptionStatus.UNBLOCKED, subscriber);
2438    }
2439   
2440    /**
2441    * This method is used to update the subscription
2442    *
2443    * @param identifier APIIdentifier
2444    * @param subStatus Subscription Status[BLOCKED/UNBLOCKED]
2445    * @param applicationId Application id
2446    * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to update subscriber
2447    */
 
2448  2 toggle public void updateSubscription(APIIdentifier identifier, String subStatus, int applicationId)
2449    throws APIManagementException {
2450   
2451  2 Connection conn = null;
2452  2 ResultSet resultSet = null;
2453  2 PreparedStatement ps = null;
2454  2 PreparedStatement updatePs = null;
2455  2 int apiId = -1;
2456   
2457  2 try {
2458  2 conn = APIMgtDBUtil.getConnection();
2459  2 conn.setAutoCommit(false);
2460   
2461  2 String getApiQuery = SQLConstants.GET_API_ID_SQL;
2462  2 ps = conn.prepareStatement(getApiQuery);
2463  2 ps.setString(1, APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
2464  2 ps.setString(2, identifier.getApiName());
2465  2 ps.setString(3, identifier.getVersion());
2466  2 resultSet = ps.executeQuery();
2467  2 if (resultSet.next()) {
2468  2 apiId = resultSet.getInt("API_ID");
2469    }
2470   
2471  2 if (apiId == -1) {
2472  0 String msg = "Unable to get the API ID for: " + identifier;
2473  0 log.error(msg);
2474  0 throw new APIManagementException(msg);
2475    }
2476   
2477  2 String subsCreateStatus = getSubscriptionCreaeteStatus(identifier, applicationId, conn);
2478   
2479  2 if (APIConstants.SubscriptionCreatedStatus.UN_SUBSCRIBE.equals(subsCreateStatus)) {
2480  0 deleteSubscriptionByApiIDAndAppID(apiId, applicationId, conn);
2481    }
2482   
2483   
2484    //This query to update the AM_SUBSCRIPTION table
2485  2 String sqlQuery = SQLConstants.UPDATE_SUBSCRIPTION_OF_APPLICATION_SQL;
2486   
2487    //Updating data to the AM_SUBSCRIPTION table
2488  2 updatePs = conn.prepareStatement(sqlQuery);
2489  2 updatePs.setString(1, subStatus);
2490  2 updatePs.setString(2, identifier.getProviderName());
2491  2 updatePs.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
2492  2 updatePs.setInt(4, apiId);
2493  2 updatePs.setInt(5, applicationId);
2494  2 updatePs.execute();
2495   
2496    // finally commit transaction
2497  2 conn.commit();
2498    } catch (SQLException e) {
2499  0 if (conn != null) {
2500  0 try {
2501  0 conn.rollback();
2502    } catch (SQLException e1) {
2503  0 log.error("Failed to rollback the add subscription ", e1);
2504    }
2505    }
2506  0 handleException("Failed to update subscription data ", e);
2507    } finally {
2508  2 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
2509  2 APIMgtDBUtil.closeAllConnections(updatePs, null, null);
2510    }
2511    }
2512   
2513    /**
2514    * This method is used to update the subscription
2515    *
2516    * @param subscribedAPI subscribedAPI object that represents the new subscription detals
2517    * @throws APIManagementException if failed to update subscription
2518    */
 
2519  0 toggle public void updateSubscription(SubscribedAPI subscribedAPI) throws APIManagementException {
2520  0 Connection conn = null;
2521  0 PreparedStatement ps = null;
2522   
2523  0 try {
2524  0 conn = APIMgtDBUtil.getConnection();
2525  0 conn.setAutoCommit(false);
2526   
2527    //This query to update the AM_SUBSCRIPTION table
2528  0 String sqlQuery = SQLConstants.UPDATE_SUBSCRIPTION_OF_UUID_SQL;
2529   
2530    //Updating data to the AM_SUBSCRIPTION table
2531  0 ps = conn.prepareStatement(sqlQuery);
2532  0 ps.setString(1, subscribedAPI.getSubStatus());
2533    //TODO Need to find logged in user who does this update.
2534  0 ps.setString(2, null);
2535  0 ps.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
2536  0 ps.setString(4, subscribedAPI.getUUID());
2537  0 ps.execute();
2538   
2539    // finally commit transaction
2540  0 conn.commit();
2541    } catch (SQLException e) {
2542  0 if (conn != null) {
2543  0 try {
2544  0 conn.rollback();
2545    } catch (SQLException e1) {
2546  0 log.error("Failed to rollback the update subscription ", e1);
2547    }
2548    }
2549  0 handleException("Failed to update subscription data ", e);
2550    } finally {
2551  0 APIMgtDBUtil.closeAllConnections(ps, conn, null);
2552    }
2553    }
2554   
 
2555  115 toggle public void updateSubscriptionStatus(int subscriptionId, String status) throws APIManagementException {
2556  115 Connection conn = null;
2557  115 PreparedStatement ps = null;
2558   
2559  115 try {
2560  115 conn = APIMgtDBUtil.getConnection();
2561  115 conn.setAutoCommit(false);
2562   
2563    //This query is to update the AM_SUBSCRIPTION table
2564  115 String sqlQuery = SQLConstants.UPDATE_SUBSCRIPTION_STATUS_SQL;
2565   
2566  115 ps = conn.prepareStatement(sqlQuery);
2567  115 ps.setString(1, status);
2568  115 ps.setInt(2, subscriptionId);
2569  115 ps.execute();
2570   
2571    //Commit transaction
2572  115 conn.commit();
2573    } catch (SQLException e) {
2574  0 if (conn != null) {
2575  0 try {
2576  0 conn.rollback();
2577    } catch (SQLException e1) {
2578  0 log.error("Failed to rollback subscription status update ", e1);
2579    }
2580    }
2581  0 handleException("Failed to update subscription status ", e);
2582    } finally {
2583  115 APIMgtDBUtil.closeAllConnections(ps, conn, null);
2584    }
2585    }
2586   
2587   
 
2588  260 toggle public String getRegistrationApprovalState(int appId, String keyType) throws APIManagementException {
2589  260 Connection conn = null;
2590  260 ResultSet resultSet = null;
2591  260 PreparedStatement ps = null;
2592  260 String state = null;
2593   
2594  260 try {
2595  260 conn = APIMgtDBUtil.getConnection();
2596  260 String sqlQuery = SQLConstants.GET_REGISTRATION_APPROVAL_STATUS_SQL;
2597   
2598  260 ps = conn.prepareStatement(sqlQuery);
2599  260 ps.setInt(1, appId);
2600  260 ps.setString(2, keyType);
2601  260 resultSet = ps.executeQuery();
2602   
2603  360 while (resultSet.next()) {
2604  100 state = resultSet.getString("STATE");
2605    }
2606    } catch (SQLException e) {
2607  0 handleException("Error while getting Application Registration State.", e);
2608    } finally {
2609  260 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
2610    }
2611  260 return state;
2612    }
2613   
2614    /**
2615    * Update the consumer key and application status for the given key type and application.
2616    *
2617    * @param application
2618    * @param keyType
2619    */
 
2620  103 toggle public void updateApplicationKeyTypeMapping(Application application, String keyType) throws APIManagementException {
2621  103 OAuthApplicationInfo app = application.getOAuthApp(keyType);
2622  103 String consumerKey = null;
2623  103 if (app != null) {
2624  103 consumerKey = app.getClientId();
2625    }
2626   
2627  103 if (consumerKey != null && application.getId() != -1) {
2628  103 String addApplicationKeyMapping = SQLConstants.UPDATE_APPLICAITON_KEY_TYPE_MAPPINGS_SQL;
2629   
2630  103 Connection connection = null;
2631  103 PreparedStatement ps = null;
2632  103 try {
2633  103 connection = APIMgtDBUtil.getConnection();
2634  103 connection.setAutoCommit(false);
2635  103 ps = connection.prepareStatement(addApplicationKeyMapping);
2636  103 ps.setString(1, consumerKey);
2637  103 ps.setInt(2, application.getId());
2638  103 ps.setString(3, keyType);
2639  103 ps.executeUpdate();
2640  103 connection.commit();
2641    } catch (SQLException e) {
2642  0 handleException("Error updating the CONSUMER KEY of the AM_APPLICATION_KEY_MAPPING table where " +
2643    "APPLICATION_ID = " + application.getId() + " and KEY_TYPE = " + keyType, e);
2644    } finally {
2645  103 APIMgtDBUtil.closeAllConnections(ps, connection, null);
2646    }
2647    }
2648    }
2649   
2650    /**
2651    * This method will create a new client at key-manager side.further it will add new record to
2652    * the AM_APPLICATION_KEY_MAPPING table
2653    *
2654    * @param keyType
2655    * @param applicationName apim application name.
2656    * @param userName apim user name
2657    * @param clientId this is the consumner key.
2658    * @throws APIManagementException
2659    */
 
2660  0 toggle public void createApplicationKeyTypeMappingForManualClients(String keyType, String applicationName, String userName,
2661    String clientId) throws APIManagementException {
2662  0 String consumerKey = null;
2663  0 if (clientId != null) {
2664  0 consumerKey = clientId;
2665    }
2666  0 Connection connection = null;
2667  0 PreparedStatement ps = null;
2668   
2669    //APIM application id.
2670  0 int applicationId = getApplicationId(applicationName, userName);
2671   
2672  0 if (consumerKey != null) {
2673  0 String addApplicationKeyMapping = SQLConstants.ADD_APPLICATION_KEY_TYPE_MAPPING_SQL;
2674  0 try {
2675  0 connection = APIMgtDBUtil.getConnection();
2676  0 connection.setAutoCommit(false);
2677  0 ps = connection.prepareStatement(addApplicationKeyMapping);
2678  0 ps.setInt(1, applicationId);
2679  0 ps.setString(2, consumerKey);
2680  0 ps.setString(3, keyType);
2681  0 ps.setString(4, APIConstants.AppRegistrationStatus.REGISTRATION_COMPLETED);
2682    // If the CK/CS pair is pasted on the screen set this to MAPPED
2683  0 ps.setString(5, "MAPPED");
2684  0 ps.execute();
2685  0 connection.commit();
2686   
2687    } catch (SQLException e) {
2688  0 handleException("Error while inserting record to the AM_APPLICATION_KEY_MAPPING table, " +
2689    "error is = " + e.getMessage(), e);
2690    } finally {
2691  0 APIMgtDBUtil.closeAllConnections(ps, connection, null);
2692    }
2693    }
2694    }
2695   
2696   
2697    /**
2698    * Updates the state of the Application Registration.
2699    *
2700    * @param state State of the registration.
2701    * @param keyType PRODUCTION | SANDBOX
2702    * @param appId ID of the Application.
2703    * @throws APIManagementException if updating fails.
2704    */
 
2705  103 toggle public void updateApplicationRegistration(String state, String keyType, int appId) throws APIManagementException {
2706  103 Connection conn = null;
2707  103 PreparedStatement ps = null;
2708   
2709  103 String sqlStmt = SQLConstants.UPDATE_APPLICATION_KEY_MAPPING_SQL;
2710  103 try {
2711  103 conn = APIMgtDBUtil.getConnection();
2712  103 conn.setAutoCommit(false);
2713   
2714  103 ps = conn.prepareStatement(sqlStmt);
2715  103 ps.setString(1, state);
2716  103 ps.setInt(2, appId);
2717  103 ps.setString(3, keyType);
2718  103 ps.execute();
2719   
2720  103 conn.commit();
2721    } catch (SQLException e) {
2722  0 handleException("Error while updating registration entry.", e);
2723    } finally {
2724  103 APIMgtDBUtil.closeAllConnections(ps, conn, null);
2725    }
2726    }
2727   
2728   
2729    /**
2730    * @param apiIdentifier APIIdentifier
2731    * @param userId User Id
2732    * @return true if user subscribed for given APIIdentifier
2733    * @throws APIManagementException if failed to check subscribed or not
2734    */
 
2735  7 toggle public boolean isSubscribed(APIIdentifier apiIdentifier, String userId) throws APIManagementException {
2736  7 boolean isSubscribed = false;
2737  7 String loginUserName = getLoginUserName(userId);
2738   
2739  7 Connection conn = null;
2740  7 PreparedStatement ps = null;
2741  7 ResultSet rs = null;
2742  7 String sqlQuery = SQLConstants.GET_SUBSCRIPTION_SQL;
2743   
2744  7 if (forceCaseInsensitiveComparisons) {
2745  7 sqlQuery = SQLConstants.GET_SUBSCRIPTION_CASE_INSENSITIVE_SQL;
2746    }
2747   
2748  7 try {
2749  7 conn = APIMgtDBUtil.getConnection();
2750  7 ps = conn.prepareStatement(sqlQuery);
2751  7 ps.setString(1, APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName()));
2752  7 ps.setString(2, apiIdentifier.getApiName());
2753  7 ps.setString(3, apiIdentifier.getVersion());
2754  7 ps.setString(4, loginUserName);
2755  7 int tenantId;
2756  7 tenantId = APIUtil.getTenantId(loginUserName);
2757  7 ps.setInt(5, tenantId);
2758   
2759  7 rs = ps.executeQuery();
2760   
2761  7 if (rs.next()) {
2762  4 isSubscribed = true;
2763    }
2764    } catch (SQLException e) {
2765  0 handleException("Error while checking if user has subscribed to the API ", e);
2766    } finally {
2767  7 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
2768    }
2769  7 return isSubscribed;
2770    }
2771   
2772    /**
2773    * @param providerName Name of the provider
2774    * @return UserApplicationAPIUsage of given provider
2775    * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to get
2776    * UserApplicationAPIUsage for given provider
2777    */
 
2778  13 toggle public UserApplicationAPIUsage[] getAllAPIUsageByProvider(String providerName) throws APIManagementException {
2779  13 Connection connection = null;
2780  13 PreparedStatement ps = null;
2781  13 ResultSet result = null;
2782   
2783  13 try {
2784  13 String sqlQuery = SQLConstants.GET_APP_API_USAGE_BY_PROVIDER_SQL;
2785  13 connection = APIMgtDBUtil.getConnection();
2786   
2787  13 ps = connection.prepareStatement(sqlQuery);
2788  13 ps.setString(1, APIUtil.replaceEmailDomainBack(providerName));
2789  13 result = ps.executeQuery();
2790   
2791  13 Map<String, UserApplicationAPIUsage> userApplicationUsages = new TreeMap<String, UserApplicationAPIUsage>();
2792  15 while (result.next()) {
2793  2 int subId = result.getInt("SUBSCRIPTION_ID");
2794  2 Map<String, String> keyData = getAccessTokenData(subId);
2795  2 String accessToken = keyData.get("token");
2796  2 String tokenStatus = keyData.get("status");
2797  2 String userId = result.getString("USER_ID");
2798  2 String application = result.getString("APPNAME");
2799  2 int appId = result.getInt("APPLICATION_ID");
2800  2 String subStatus = result.getString("SUB_STATUS");
2801  2 String subsCreateState = result.getString("SUBS_CREATE_STATE");
2802  2 String key = userId + "::" + application;
2803  2 UserApplicationAPIUsage usage = userApplicationUsages.get(key);
2804  2 if (usage == null) {
2805  2 usage = new UserApplicationAPIUsage();
2806  2 usage.setUserId(userId);
2807  2 usage.setApplicationName(application);
2808  2 usage.setAppId(appId);
2809  2 usage.setAccessToken(accessToken);
2810  2 usage.setAccessTokenStatus(tokenStatus);
2811  2 userApplicationUsages.put(key, usage);
2812    }
2813  2 APIIdentifier apiId = new APIIdentifier(result.getString("API_PROVIDER"), result.getString
2814    ("API_NAME"), result.getString("API_VERSION"));
2815  2 SubscribedAPI apiSubscription = new SubscribedAPI(new Subscriber(userId), apiId);
2816  2 apiSubscription.setSubStatus(subStatus);
2817  2 apiSubscription.setSubCreatedStatus(subsCreateState);
2818  2 apiSubscription.setUUID(result.getString("SUB_UUID"));
2819  2 apiSubscription.setTier(new Tier(result.getString("SUB_TIER_ID")));
2820  2 Application applicationObj = new Application(result.getString("APP_UUID"));
2821  2 apiSubscription.setApplication(applicationObj);
2822  2 usage.addApiSubscriptions(apiSubscription);
2823    }
2824  13 return userApplicationUsages.values().toArray(new UserApplicationAPIUsage[userApplicationUsages.size()]);
2825    } catch (SQLException e) {
2826  0 handleException("Failed to find API Usage for :" + providerName, e);
2827  0 return null;
2828    } finally {
2829  13 APIMgtDBUtil.closeAllConnections(ps, connection, result);
2830    }
2831    }
2832   
2833    /**
2834    * @param apiName Name of the API
2835    * @param apiVersion Version of the API
2836    * @param provider Name of API creator
2837    * @return All subscriptions of a given API
2838    * @throws org.wso2.carbon.apimgt.api.APIManagementException
2839    */
 
2840  10 toggle public List<SubscribedAPI> getSubscriptionsOfAPI(String apiName, String apiVersion, String provider)
2841    throws APIManagementException {
2842  10 Connection connection = null;
2843  10 PreparedStatement ps = null;
2844  10 ResultSet result = null;
2845  10 List<SubscribedAPI> subscriptions = new ArrayList<>();
2846   
2847  10 try {
2848  10 String sqlQuery = SQLConstants.GET_SUBSCRIPTIONS_OF_API_SQL;
2849  10 connection = APIMgtDBUtil.getConnection();
2850   
2851  10 ps = connection.prepareStatement(sqlQuery);
2852  10 ps.setString(1, apiName);
2853  10 ps.setString(2, apiVersion);
2854  10 ps.setString(3, provider);
2855  10 result = ps.executeQuery();
2856   
2857  17 while (result.next()) {
2858  7 APIIdentifier apiId = new APIIdentifier(result.getString("API_PROVIDER"), apiName, apiVersion);
2859  7 Subscriber subscriber = new Subscriber(result.getString("USER_ID"));
2860  7 SubscribedAPI subscription = new SubscribedAPI(subscriber, apiId);
2861  7 subscription.setUUID(result.getString("SUB_UUID"));
2862  7 subscription.setSubStatus(result.getString("SUB_STATUS"));
2863  7 subscription.setSubCreatedStatus(result.getString("SUBS_CREATE_STATE"));
2864  7 subscription.setTier(new Tier(result.getString("SUB_TIER_ID")));
2865  7 subscription.setCreatedTime(result.getString("SUB_CREATED_TIME"));
2866   
2867  7 Application application = new Application(result.getInt("APPLICATION_ID"));
2868  7 application.setName(result.getString("APPNAME"));
2869  7 subscription.setApplication(application);
2870   
2871  7 subscriptions.add(subscription);
2872    }
2873    } catch (SQLException e) {
2874  0 handleException("Error occurred while reading subscriptions of API: " + apiName + ':' + apiVersion, e);
2875    } finally {
2876  10 APIMgtDBUtil.closeAllConnections(ps, connection, result);
2877    }
2878  10 return subscriptions;
2879    }
2880   
 
2881  15 toggle private void updateOAuthConsumerApp(String appName, String callbackUrl)
2882    throws IdentityOAuthAdminException, APIManagementException {
2883  15 Connection connection = null;
2884  15 PreparedStatement prepStmt = null;
2885  15 String sqlStmt = SQLConstants.UPDATE_OAUTH_CONSUMER_SQL;
2886  15 try {
2887  15 connection = APIMgtDBUtil.getConnection();
2888  15 connection.setAutoCommit(false);
2889   
2890  15 prepStmt = connection.prepareStatement(sqlStmt);
2891  15 prepStmt.setString(1, callbackUrl);
2892  15 prepStmt.setString(2, appName);
2893  15 prepStmt.execute();
2894   
2895  15 connection.commit();
2896    } catch (SQLException e) {
2897  0 handleException("Error when updating OAuth consumer App for " + appName, e);
2898    } finally {
2899  15 APIMgtDBUtil.closeAllConnections(prepStmt, connection, null);
2900    }
2901    }
2902   
 
2903  0 toggle private boolean isDuplicateConsumer(String consumerKey) throws APIManagementException {
2904  0 Connection connection = null;
2905  0 PreparedStatement prepStmt = null;
2906  0 ResultSet rSet = null;
2907  0 String sqlQuery = SQLConstants.GET_ALL_OAUTH_CONSUMER_APPS_SQL;
2908   
2909  0 boolean isDuplicateConsumer = false;
2910  0 try {
2911  0 connection = APIMgtDBUtil.getConnection();
2912  0 prepStmt = connection.prepareStatement(sqlQuery);
2913  0 prepStmt.setString(1, consumerKey);
2914   
2915  0 rSet = prepStmt.executeQuery();
2916  0 if (rSet.next()) {
2917  0 isDuplicateConsumer = true;
2918    }
2919    } catch (SQLException e) {
2920  0 handleException("Error when reading the application information from" + " the persistence store.", e);
2921    } finally {
2922  0 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rSet);
2923    }
2924  0 return isDuplicateConsumer;
2925    }
2926   
 
2927  167 toggle public int addApplication(Application application, String userId) throws APIManagementException {
2928  167 Connection conn = null;
2929  167 int applicationId = 0;
2930  167 String loginUserName = getLoginUserName(userId);
2931  167 try {
2932  167 conn = APIMgtDBUtil.getConnection();
2933  167 conn.setAutoCommit(false);
2934  167 applicationId = addApplication(application, loginUserName, conn);
2935   
2936  167 if (multiGroupAppSharingEnabled) {
2937  0 Subscriber subscriber = getSubscriber(userId);
2938  0 String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
2939  0 updateGroupIDMappings(conn, applicationId, application.getGroupId(),
2940    tenantDomain);
2941    }
2942  167 conn.commit();
2943    } catch (SQLException e) {
2944  0 if (conn != null) {
2945  0 try {
2946  0 conn.rollback();
2947    } catch (SQLException e1) {
2948  0 log.error("Failed to rollback the add Application ", e1);
2949    }
2950    }
2951  0 handleException("Failed to add Application", e);
2952    } finally {
2953  167 APIMgtDBUtil.closeAllConnections(null, conn, null);
2954    }
2955  167 return applicationId;
2956    }
2957   
 
2958  2 toggle public void addRating(APIIdentifier apiId, int rating, String user) throws APIManagementException {
2959  2 Connection conn = null;
2960  2 try {
2961  2 conn = APIMgtDBUtil.getConnection();
2962  2 conn.setAutoCommit(false);
2963  2 addRating(apiId, rating, user, conn);
2964   
2965  2 conn.commit();
2966    } catch (SQLException e) {
2967  0 if (conn != null) {
2968  0 try {
2969  0 conn.rollback();
2970    } catch (SQLException e1) {
2971  0 log.error("Failed to rollback the add Application ", e1);
2972    }
2973    }
2974  0 handleException("Failed to add Application", e);
2975    } finally {
2976  2 APIMgtDBUtil.closeAllConnections(null, conn, null);
2977    }
2978    }
2979   
2980    /**
2981    * @param apiIdentifier API Identifier
2982    * @param userId User Id
2983    * @throws APIManagementException if failed to add Application
2984    */
 
2985  2 toggle public void addRating(APIIdentifier apiIdentifier, int rating, String userId, Connection conn)
2986    throws APIManagementException, SQLException {
2987  2 PreparedStatement ps = null;
2988  2 PreparedStatement psSelect = null;
2989  2 ResultSet rs = null;
2990   
2991  2 try {
2992  2 int tenantId;
2993  2 tenantId = APIUtil.getTenantId(userId);
2994    //Get subscriber Id
2995  2 Subscriber subscriber = getSubscriber(userId, tenantId, conn);
2996  2 if (subscriber == null) {
2997  0 String msg = "Could not load Subscriber records for: " + userId;
2998  0 log.error(msg);
2999  0 throw new APIManagementException(msg);
3000    }
3001  2 int apiId;
3002  2 apiId = getAPIID(apiIdentifier, conn);
3003  2 if (apiId == -1) {
3004  0 String msg = "Could not load API record for: " + apiIdentifier.getApiName();
3005  0 log.error(msg);
3006  0 throw new APIManagementException(msg);
3007    }
3008  2 boolean userRatingExists = false;
3009    //This query to check the ratings already exists for the user in the AM_API_RATINGS table
3010  2 String sqlQuery = SQLConstants.GET_API_RATING_SQL;
3011   
3012  2 psSelect = conn.prepareStatement(sqlQuery);
3013  2 psSelect.setInt(1, apiId);
3014  2 psSelect.setInt(2, subscriber.getId());
3015  2 rs = psSelect.executeQuery();
3016   
3017  2 while (rs.next()) {
3018  0 userRatingExists = true;
3019    }
3020   
3021  2 String sqlAddQuery;
3022  2 if (!userRatingExists) {
3023    //This query to update the AM_API_RATINGS table
3024  2 sqlAddQuery = SQLConstants.APP_API_RATING_SQL;
3025    } else {
3026    //This query to insert into the AM_API_RATINGS table
3027  0 sqlAddQuery = SQLConstants.UPDATE_API_RATING_SQL;
3028    }
3029    // Adding data to the AM_API_RATINGS table
3030  2 ps = conn.prepareStatement(sqlAddQuery);
3031  2 ps.setInt(1, rating);
3032  2 ps.setInt(2, apiId);
3033  2 ps.setInt(3, subscriber.getId());
3034  2 ps.executeUpdate();
3035   
3036    } catch (SQLException e) {
3037  0 handleException("Failed to add API rating of the user:" + userId, e);
3038    } finally {
3039  2 APIMgtDBUtil.closeAllConnections(ps, null, rs);
3040  2 APIMgtDBUtil.closeAllConnections(psSelect, null, null);
3041    }
3042    }
3043   
 
3044  2 toggle public void removeAPIRating(APIIdentifier apiId, String user) throws APIManagementException {
3045  2 Connection conn = null;
3046  2 try {
3047  2 conn = APIMgtDBUtil.getConnection();
3048  2 conn.setAutoCommit(false);
3049   
3050  2 removeAPIRating(apiId, user, conn);
3051   
3052  2 conn.commit();
3053    } catch (SQLException e) {
3054  0 if (conn != null) {
3055  0 try {
3056  0 conn.rollback();
3057    } catch (SQLException e1) {
3058  0 log.error("Failed to rollback the add Application ", e1);
3059    }
3060    }
3061  0 handleException("Failed to add Application", e);
3062    } finally {
3063  2 APIMgtDBUtil.closeAllConnections(null, conn, null);
3064    }
3065    }
3066   
3067    /**
3068    * @param apiIdentifier API Identifier
3069    * @param userId User Id
3070    * @throws APIManagementException if failed to add Application
3071    */
 
3072  2 toggle public void removeAPIRating(APIIdentifier apiIdentifier, String userId, Connection conn)
3073    throws APIManagementException, SQLException {
3074  2 PreparedStatement ps = null;
3075  2 PreparedStatement psSelect = null;
3076  2 ResultSet rs = null;
3077   
3078  2 try {
3079  2 int tenantId;
3080  2 int rateId = -1;
3081  2 tenantId = APIUtil.getTenantId(userId);
3082    //Get subscriber Id
3083  2 Subscriber subscriber = getSubscriber(userId, tenantId, conn);
3084  2 if (subscriber == null) {
3085  0 String msg = "Could not load Subscriber records for: " + userId;
3086  0 log.error(msg);
3087  0 throw new APIManagementException(msg);
3088    }
3089    //Get API Id
3090  2 int apiId = -1;
3091  2 apiId = getAPIID(apiIdentifier, conn);
3092  2 if (apiId == -1) {
3093  0 String msg = "Could not load API record for: " + apiIdentifier.getApiName();
3094  0 log.error(msg);
3095  0 throw new APIManagementException(msg);
3096    }
3097   
3098    //This query to check the ratings already exists for the user in the AM_API_RATINGS table
3099  2 String sqlQuery = SQLConstants.GET_RATING_ID_SQL;
3100   
3101  2 psSelect = conn.prepareStatement(sqlQuery);
3102  2 psSelect.setInt(1, apiId);
3103  2 psSelect.setInt(2, subscriber.getId());
3104  2 rs = psSelect.executeQuery();
3105   
3106  4 while (rs.next()) {
3107  2 rateId = rs.getInt("RATING_ID");
3108    }
3109  2 String sqlAddQuery;
3110  2 if (rateId != -1) {
3111    //This query to delete the specific rate row from the AM_API_RATINGS table
3112  2 sqlAddQuery = SQLConstants.REMOVE_RATING_SQL;
3113    // Adding data to the AM_API_RATINGS table
3114  2 ps = conn.prepareStatement(sqlAddQuery);
3115  2 ps.setInt(1, rateId);
3116  2 ps.executeUpdate();
3117    }
3118    } catch (SQLException e) {
3119  0 handleException("Failed to delete API rating", e);
3120    } finally {
3121  2 APIMgtDBUtil.closeAllConnections(ps, null, null);
3122  2 APIMgtDBUtil.closeAllConnections(psSelect, null, rs);
3123    }
3124    }
3125   
 
3126  7 toggle public int getUserRating(APIIdentifier apiId, String user) throws APIManagementException {
3127  7 Connection conn = null;
3128  7 int userRating = 0;
3129  7 try {
3130  7 conn = APIMgtDBUtil.getConnection();
3131  7 conn.setAutoCommit(false);
3132   
3133  7 userRating = getUserRating(apiId, user, conn);
3134   
3135  7 conn.commit();
3136    } catch (SQLException e) {
3137  0 if (conn != null) {
3138  0 try {
3139  0 conn.rollback();
3140    } catch (SQLException e1) {
3141  0 log.error("Failed to rollback getting user ratings ", e1);
3142    }
3143    }
3144  0 handleException("Failed to get user ratings", e);
3145    } finally {
3146  7 APIMgtDBUtil.closeAllConnections(null, conn, null);
3147    }
3148  7 return userRating;
3149    }
3150   
3151    /**
3152    * @param apiIdentifier API Identifier
3153    * @param userId User Id
3154    * @throws APIManagementException if failed to add Application
3155    */
 
3156  7 toggle public int getUserRating(APIIdentifier apiIdentifier, String userId, Connection conn)
3157    throws APIManagementException, SQLException {
3158  7 PreparedStatement ps = null;
3159  7 ResultSet rs = null;
3160  7 int userRating = 0;
3161  7 try {
3162  7 int tenantId;
3163  7 tenantId = APIUtil.getTenantId(userId);
3164    //Get subscriber Id
3165  7 Subscriber subscriber = getSubscriber(userId, tenantId, conn);
3166  7 if (subscriber == null) {
3167  0 String msg = "Could not load Subscriber records for: " + userId;
3168  0 log.error(msg);
3169  0 throw new APIManagementException(msg);
3170    }
3171    //Get API Id
3172  7 int apiId = -1;
3173  7 apiId = getAPIID(apiIdentifier, conn);
3174  7 if (apiId == -1) {
3175  0 String msg = "Could not load API record for: " + apiIdentifier.getApiName();
3176  0 log.error(msg);
3177  0 throw new APIManagementException(msg);
3178    }
3179    //This query to update the AM_API_RATINGS table
3180  7 String sqlQuery = SQLConstants.GET_RATING_SQL;
3181    // Adding data to the AM_API_RATINGS table
3182  7 ps = conn.prepareStatement(sqlQuery);
3183  7 ps.setInt(1, subscriber.getId());
3184  7 ps.setInt(2, apiId);
3185  7 rs = ps.executeQuery();
3186   
3187  7 while (rs.next()) {
3188  0 userRating = rs.getInt("RATING");
3189    }
3190   
3191    } catch (SQLException e) {
3192  0 handleException("Failed to add Application", e);
3193    } finally {
3194  7 APIMgtDBUtil.closeAllConnections(ps, null, rs);
3195    }
3196  7 return userRating;
3197    }
3198   
 
3199  0 toggle public float getAverageRating(APIIdentifier apiId) throws APIManagementException {
3200  0 Connection conn = null;
3201  0 float avrRating = 0;
3202  0 try {
3203  0 conn = APIMgtDBUtil.getConnection();
3204  0 conn.setAutoCommit(false);
3205   
3206  0 avrRating = getAverageRating(apiId, conn);
3207    } catch (SQLException e) {
3208  0 if (conn != null) {
3209  0 try {
3210  0 conn.rollback();
3211    } catch (SQLException e1) {
3212  0 log.error("Failed to rollback getting user ratings ", e1);
3213    }
3214    }
3215  0 handleException("Failed to get user ratings", e);
3216    } finally {
3217  0 APIMgtDBUtil.closeAllConnections(null, conn, null);
3218    }
3219  0 return avrRating;
3220    }
3221   
 
3222  3557 toggle public float getAverageRating(int apiId) throws APIManagementException {
3223  3557 Connection conn = null;
3224  3557 float avrRating = 0;
3225  3557 PreparedStatement ps = null;
3226  3557 ResultSet rs = null;
3227  3557 try {
3228  3557 conn = APIMgtDBUtil.getConnection();
3229  3557 conn.setAutoCommit(false);
3230   
3231  3557 if (apiId == -1) {
3232  0 String msg = "Invalid APIId : " + apiId;
3233  0 log.error(msg);
3234  0 return Float.NEGATIVE_INFINITY;
3235    }
3236    //This query to update the AM_API_RATINGS table
3237  3557 String sqlQuery = SQLConstants.GET_AVERAGE_RATING_SQL;
3238   
3239  3557 ps = conn.prepareStatement(sqlQuery);
3240  3557 ps.setInt(1, apiId);
3241  3557 rs = ps.executeQuery();
3242   
3243  3559 while (rs.next()) {
3244  2 avrRating = rs.getFloat("RATING");
3245    }
3246    } catch (SQLException e) {
3247  0 if (conn != null) {
3248  0 try {
3249  0 conn.rollback();
3250    } catch (SQLException e1) {
3251  0 log.error("Failed to rollback getting user ratings ", e1);
3252    }
3253    }
3254  0 handleException("Failed to get user ratings", e);
3255    } finally {
3256  3557 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
3257    }
3258  3557 return avrRating;
3259    }
3260   
3261    /**
3262    * @param apiIdentifier API Identifier
3263    * @throws APIManagementException if failed to add Application
3264    */
 
3265  0 toggle public float getAverageRating(APIIdentifier apiIdentifier, Connection conn)
3266    throws APIManagementException, SQLException {
3267  0 PreparedStatement ps = null;
3268  0 ResultSet rs = null;
3269  0 float avrRating = 0;
3270  0 try {
3271    //Get API Id
3272  0 int apiId;
3273  0 apiId = getAPIID(apiIdentifier, conn);
3274  0 if (apiId == -1) {
3275  0 String msg = "Could not load API record for: " + apiIdentifier.getApiName();
3276  0 log.error(msg);
3277  0 return Float.NEGATIVE_INFINITY;
3278    }
3279    //This query to update the AM_API_RATINGS table
3280  0 String sqlQuery = SQLConstants.GET_AVERAGE_RATING_SQL;
3281   
3282  0 ps = conn.prepareStatement(sqlQuery);
3283  0 ps.setInt(1, apiId);
3284  0 rs = ps.executeQuery();
3285   
3286  0 while (rs.next()) {
3287  0 avrRating = rs.getFloat("RATING");
3288    }
3289   
3290    } catch (SQLException e) {
3291  0 handleException("Failed to add Application", e);
3292    } finally {
3293  0 APIMgtDBUtil.closeAllConnections(ps, null, rs);
3294    }
3295   
3296  0 BigDecimal decimal = new BigDecimal(avrRating);
3297  0 return Float.parseFloat(decimal.setScale(1, BigDecimal.ROUND_UP).toString());
3298    }
3299   
3300    /**
3301    * @param application Application
3302    * @param userId User Id
3303    * @throws APIManagementException if failed to add Application
3304    */
 
3305  167 toggle public int addApplication(Application application, String userId, Connection conn)
3306    throws APIManagementException, SQLException {
3307  167 PreparedStatement ps = null;
3308  167 conn.setAutoCommit(false);
3309  167 ResultSet rs = null;
3310   
3311  167 int applicationId = 0;
3312  167 try {
3313  167 int tenantId = APIUtil.getTenantId(userId);
3314   
3315    //Get subscriber Id
3316  167 Subscriber subscriber = getSubscriber(userId, tenantId, conn);
3317  167 if (subscriber == null) {
3318  0 String msg = "Could not load Subscriber records for: " + userId;
3319  0 log.error(msg);
3320  0 throw new APIManagementException(msg);
3321    }
3322    //This query to update the AM_APPLICATION table
3323  167 String sqlQuery = SQLConstants.APP_APPLICATION_SQL;
3324    // Adding data to the AM_APPLICATION table
3325    //ps = conn.prepareStatement(sqlQuery);
3326  167 ps = conn.prepareStatement(sqlQuery, new String[]{"APPLICATION_ID"});
3327  167 if (conn.getMetaData().getDriverName().contains("PostgreSQL")) {
3328  0 ps = conn.prepareStatement(sqlQuery, new String[]{"application_id"});
3329    }
3330   
3331  167 ps.setString(1, application.getName());
3332  167 ps.setInt(2, subscriber.getId());
3333  167 ps.setString(3, application.getTier());
3334  167 ps.setString(4, application.getCallbackUrl());
3335  167 ps.setString(5, application.getDescription());
3336   
3337  167 if (APIConstants.DEFAULT_APPLICATION_NAME.equals(application.getName())) {
3338  34 ps.setString(6, APIConstants.ApplicationStatus.APPLICATION_APPROVED);
3339    } else {
3340  133 ps.setString(6, APIConstants.ApplicationStatus.APPLICATION_CREATED);
3341    }
3342   
3343  167 String groupId = application.getGroupId();
3344  167 if (multiGroupAppSharingEnabled) {
3345    // setting an empty groupId since groupid's should be saved in groupId mapping table
3346  0 groupId = "";
3347    }
3348  167 ps.setString(7, groupId);
3349  167 ps.setString(8, subscriber.getName());
3350   
3351  167 Timestamp timestamp = new Timestamp(System.currentTimeMillis());
3352  167 ps.setTimestamp(9, timestamp);
3353  167 ps.setTimestamp(10, timestamp);
3354  167 ps.setString(11, UUID.randomUUID().toString());
3355  167 ps.setString(12, String.valueOf(application.getTokenType()));
3356  167 ps.executeUpdate();
3357   
3358  167 rs = ps.getGeneratedKeys();
3359  334 while (rs.next()) {
3360  167 applicationId = Integer.parseInt(rs.getString(1));
3361    }
3362   
3363    //Adding data to AM_APPLICATION_ATTRIBUTES table
3364  167 if( application.getApplicationAttributes() != null) {
3365  157 addApplicationAttributes(conn, application.getApplicationAttributes(), applicationId, tenantId);
3366    }
3367    } catch (SQLException e) {
3368  0 handleException("Failed to add Application", e);
3369    } finally {
3370  167 APIMgtDBUtil.closeAllConnections(ps, null, rs);
3371    }
3372  167 return applicationId;
3373    }
3374   
 
3375  15 toggle public void updateApplication(Application application) throws APIManagementException {
3376  15 Connection conn = null;
3377  15 PreparedStatement ps = null;
3378  15 PreparedStatement preparedStatement = null;
3379  15 try {
3380  15 conn = APIMgtDBUtil.getConnection();
3381  15 conn.setAutoCommit(false);
3382   
3383    //This query to update the AM_APPLICATION table
3384  15 String sqlQuery = SQLConstants.UPDATE_APPLICATION_SQL;
3385    // Adding data to the AM_APPLICATION table
3386  15 ps = conn.prepareStatement(sqlQuery);
3387  15 ps.setString(1, application.getName());
3388  15 ps.setString(2, application.getTier());
3389  15 ps.setString(3, application.getCallbackUrl());
3390  15 ps.setString(4, application.getDescription());
3391    //TODO need to find the proper user who updates this application.
3392  15 ps.setString(5, null);
3393  15 ps.setTimestamp(6, new Timestamp(System.currentTimeMillis()));
3394  15 ps.setString(7, application.getTokenType());
3395  15 ps.setInt(8, application.getId());
3396   
3397  15 ps.executeUpdate();
3398   
3399  15 if (multiGroupAppSharingEnabled) {
3400  0 Subscriber subscriber = application.getSubscriber();
3401  0 String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
3402  0 updateGroupIDMappings(conn, application.getId(), application.getGroupId(),
3403    tenantDomain);
3404    }
3405  15 Subscriber subscriber = application.getSubscriber();
3406  15 String domain = MultitenantUtils.getTenantDomain(subscriber.getName());
3407  15 int tenantId = IdentityTenantUtil.getTenantId(domain);
3408   
3409  15 preparedStatement = conn.prepareStatement(SQLConstants.REMOVE_APPLICATION_ATTRIBUTES_SQL);
3410  15 preparedStatement.setInt(1,application.getId());
3411  15 preparedStatement.execute();
3412   
3413  15 if (log.isDebugEnabled()) {
3414  0 log.debug("Old attributes of application - " + application.getName() + " are removed");
3415    }
3416   
3417  15 if (application.getApplicationAttributes() != null && !application.getApplicationAttributes().isEmpty()) {
3418  0 addApplicationAttributes(conn, application.getApplicationAttributes(), application.getId(), tenantId);
3419    }
3420  15 conn.commit();
3421  15 updateOAuthConsumerApp(application.getName(), application.getCallbackUrl());
3422    } catch (SQLException e) {
3423  0 if (conn != null) {
3424  0 try {
3425  0 conn.rollback();
3426    } catch (SQLException e1) {
3427  0 log.error("Failed to rollback the update Application ", e1);
3428    }
3429    }
3430  0 handleException("Failed to update Application", e);
3431    } catch (IdentityOAuthAdminException e) {
3432  0 handleException("Failed to update OAuth Consumer Application", e);
3433    } finally {
3434  15 APIMgtDBUtil.closeAllConnections(ps, null, null);
3435  15 APIMgtDBUtil.closeAllConnections(preparedStatement,conn,null);
3436    }
3437    }
3438   
3439    /**
3440    * Update the status of the Application creation process
3441    *
3442    * @param applicationId
3443    * @param status
3444    * @throws APIManagementException
3445    */
 
3446  133 toggle public void updateApplicationStatus(int applicationId, String status) throws APIManagementException {
3447  133 Connection conn = null;
3448  133 PreparedStatement ps = null;
3449   
3450  133 try {
3451  133 conn = APIMgtDBUtil.getConnection();
3452  133 conn.setAutoCommit(false);
3453   
3454  133 String updateSqlQuery = SQLConstants.UPDATE_APPLICATION_STATUS_SQL;
3455   
3456  133 ps = conn.prepareStatement(updateSqlQuery);
3457  133 ps.setString(1, status);
3458  133 ps.setInt(2, applicationId);
3459   
3460  133 ps.executeUpdate();
3461   
3462  133 conn.commit();
3463    } catch (SQLException e) {
3464  0 if (conn != null) {
3465  0 try {
3466  0 conn.rollback();
3467    } catch (SQLException e1) {
3468  0 log.error("Failed to rollback the update Application ", e1);
3469    }
3470    }
3471  0 handleException("Failed to update Application", e);
3472    } finally {
3473  133 APIMgtDBUtil.closeAllConnections(ps, conn, null);
3474    }
3475    }
3476   
3477    /**
3478    * get the status of the Application creation process
3479    *
3480    * @param appName
3481    * @return
3482    * @throws APIManagementException
3483    */
 
3484  0 toggle public String getApplicationStatus(String appName, String userId) throws APIManagementException {
3485  0 int applicationId = getApplicationId(appName, userId);
3486  0 return getApplicationStatusById(applicationId);
3487    }
3488   
3489    /**
3490    * get the status of the Application creation process given the application Id
3491    *
3492    * @param applicationId Id of the Application
3493    * @return
3494    * @throws APIManagementException
3495    */
 
3496  122 toggle public String getApplicationStatusById(int applicationId) throws APIManagementException {
3497  122 Connection conn = null;
3498  122 ResultSet resultSet = null;
3499  122 PreparedStatement ps = null;
3500  122 String status = null;
3501  122 try {
3502  122 conn = APIMgtDBUtil.getConnection();
3503  122 conn.setAutoCommit(false);
3504   
3505  122 String sqlQuery = SQLConstants.GET_APPLICATION_STATUS_BY_ID_SQL;
3506   
3507  122 ps = conn.prepareStatement(sqlQuery);
3508  122 ps.setInt(1, applicationId);
3509  122 resultSet = ps.executeQuery();
3510  244 while (resultSet.next()) {
3511  122 status = resultSet.getString("APPLICATION_STATUS");
3512    }
3513   
3514  122 conn.commit();
3515    } catch (SQLException e) {
3516  0 if (conn != null) {
3517  0 try {
3518  0 conn.rollback();
3519    } catch (SQLException e1) {
3520  0 log.error("Failed to rollback the update Application ", e1);
3521    }
3522    }
3523  0 handleException("Failed to update Application", e);
3524    } finally {
3525  122 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
3526    }
3527  122 return status;
3528    }
3529   
3530    /**
3531    * Check whether given application name is available under current subscriber or group
3532    *
3533    * @param appName application name
3534    * @param username subscriber
3535    * @param groupId group of the subscriber
3536    * @return true if application is available for the subscriber
3537    * @throws APIManagementException if failed to get applications for given subscriber
3538    */
 
3539  152 toggle public boolean isApplicationExist(String appName, String username, String groupId) throws APIManagementException {
3540  152 if (username == null) {
3541  0 return false;
3542    }
3543  152 Subscriber subscriber = getSubscriber(username);
3544   
3545  152 Connection connection = null;
3546  152 PreparedStatement preparedStatement = null;
3547  152 ResultSet resultSet = null;
3548  152 int appId = 0;
3549   
3550  152 String sqlQuery = SQLConstants.GET_APPLICATION_ID_PREFIX;
3551   
3552  152 String whereClauseWithGroupId = " AND (APP.GROUP_ID = ? OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL)"
3553    + " AND SUB.USER_ID = ?))";
3554  152 String whereClauseWithGroupIdCaseInsensitive = " AND (APP.GROUP_ID = ? "
3555    + "OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL) AND LOWER(SUB.USER_ID) = LOWER(?)))";
3556   
3557  152 String whereClauseWithMultiGroupId = " AND ( (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM " +
3558    "AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?)) OR ( SUB.USER_ID = ? ) " +
3559    "OR (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM AM_APPLICATION WHERE GROUP_ID = ?)))";
3560   
3561  152 String whereClauseWithMultiGroupIdCaseInsensitive = " AND ( (APP.APPLICATION_ID IN (SELECT APPLICATION_ID " +
3562    "FROM AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?)) " +
3563    "OR (LOWER(SUB.USER_ID) = LOWER(?))" +
3564    "OR (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM AM_APPLICATION WHERE GROUP_ID = ?)))";
3565   
3566   
3567  152 String whereClause = " AND SUB.USER_ID = ? ";
3568  152 String whereClauseCaseInsensitive = " AND LOWER(SUB.USER_ID) = LOWER(?) ";
3569   
3570  152 try {
3571  152 connection = APIMgtDBUtil.getConnection();
3572   
3573  152 if (!StringUtils.isEmpty(groupId)) {
3574  0 if (multiGroupAppSharingEnabled) {
3575  0 if (forceCaseInsensitiveComparisons) {
3576  0 sqlQuery += whereClauseWithMultiGroupIdCaseInsensitive;
3577    } else {
3578  0 sqlQuery += whereClauseWithMultiGroupId;
3579    }
3580  0 String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
3581  0 String[] grpIdArray = groupId.split(",");
3582  0 int noOfParams = grpIdArray.length;
3583  0 preparedStatement = fillQueryParams(connection, sqlQuery, grpIdArray, 2);
3584  0 preparedStatement.setString(1, appName);
3585  0 int paramIndex = noOfParams + 1;
3586  0 preparedStatement.setString(++paramIndex, tenantDomain);
3587  0 preparedStatement.setString(++paramIndex, subscriber.getName());
3588  0 preparedStatement.setString(++paramIndex, tenantDomain + '/' + groupId);
3589    } else {
3590  0 if (forceCaseInsensitiveComparisons) {
3591  0 sqlQuery += whereClauseWithGroupIdCaseInsensitive;
3592    } else {
3593  0 sqlQuery += whereClauseWithGroupId;
3594    }
3595  0 preparedStatement = connection.prepareStatement(sqlQuery);
3596  0 preparedStatement.setString(1, appName);
3597  0 preparedStatement.setString(2, groupId);
3598  0 preparedStatement.setString(3, subscriber.getName());
3599    }
3600    } else {
3601  152 if (forceCaseInsensitiveComparisons) {
3602  152 sqlQuery += whereClauseCaseInsensitive;
3603    } else {
3604  0 sqlQuery += whereClause;
3605    }
3606  152 preparedStatement = connection.prepareStatement(sqlQuery);
3607  152 preparedStatement.setString(1, appName);
3608  152 preparedStatement.setString(2, subscriber.getName());
3609    }
3610   
3611  152 resultSet = preparedStatement.executeQuery();
3612   
3613  152 if (resultSet.next()) {
3614  16 appId = resultSet.getInt("APPLICATION_ID");
3615    }
3616   
3617  152 if (appId > 0) {
3618  16 return true;
3619    }
3620   
3621    } catch (SQLException e) {
3622  0 handleException("Error while getting the id of " + appName + " from the persistence store.", e);
3623    } finally {
3624  152 APIMgtDBUtil.closeAllConnections(preparedStatement, connection, resultSet);
3625    }
3626  136 return false;
3627    }
3628   
3629   
3630    /**
3631    * @param username Subscriber
3632    * @return ApplicationId for given appname.
3633    * @throws APIManagementException if failed to get Applications for given subscriber.
3634    */
 
3635  110 toggle public int getApplicationId(String appName, String username) throws APIManagementException {
3636  110 if (username == null) {
3637  0 return 0;
3638    }
3639  110 Subscriber subscriber = getSubscriber(username);
3640   
3641  110 Connection connection = null;
3642  110 PreparedStatement prepStmt = null;
3643  110 ResultSet rs = null;
3644  110 int appId = 0;
3645   
3646  110 String sqlQuery = SQLConstants.GET_APPLICATION_ID_SQL;
3647  110 try {
3648  110 connection = APIMgtDBUtil.getConnection();
3649  110 prepStmt = connection.prepareStatement(sqlQuery);
3650  110 prepStmt.setInt(1, subscriber.getId());
3651  110 prepStmt.setString(2, appName);
3652  110 rs = prepStmt.executeQuery();
3653   
3654   
3655  219 while (rs.next()) {
3656  109 appId = rs.getInt("APPLICATION_ID");
3657    }
3658   
3659    } catch (SQLException e) {
3660  0 handleException("Error when getting the application id from" + " the persistence store.", e);
3661    } finally {
3662  110 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
3663    }
3664  110 return appId;
3665    }
3666   
3667    /**
3668    * Find the name of the application by Id
3669    *
3670    * @param applicationId - applicatoin id
3671    * @return - application name
3672    * @throws APIManagementException
3673    */
 
3674  294 toggle public String getApplicationNameFromId(int applicationId) throws APIManagementException {
3675   
3676  294 Connection connection = null;
3677  294 PreparedStatement prepStmt = null;
3678  294 ResultSet rs = null;
3679  294 String appName = null;
3680   
3681  294 String sqlQuery = SQLConstants.GET_APPLICATION_NAME_FROM_ID_SQL;
3682   
3683  294 try {
3684  294 connection = APIMgtDBUtil.getConnection();
3685  294 prepStmt = connection.prepareStatement(sqlQuery);
3686  294 prepStmt.setInt(1, applicationId);
3687  294 rs = prepStmt.executeQuery();
3688   
3689  588 while (rs.next()) {
3690  294 appName = rs.getString("NAME");
3691    }
3692   
3693    } catch (SQLException e) {
3694  0 handleException("Error when getting the application name for id " + applicationId, e);
3695    } finally {
3696  294 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
3697    }
3698  294 return appName;
3699    }
3700   
 
3701  0 toggle public int getAllApplicationCount(Subscriber subscriber, String groupingId, String search) throws APIManagementException {
3702   
3703  0 Connection connection = null;
3704  0 PreparedStatement prepStmt = null;
3705  0 ResultSet resultSet = null;
3706  0 String sqlQuery = null;
3707   
3708  0 try {
3709  0 connection = APIMgtDBUtil.getConnection();
3710  0 if (groupingId != null && !"null".equals(groupingId) && !groupingId.isEmpty()) {
3711   
3712  0 if (multiGroupAppSharingEnabled) {
3713  0 if (forceCaseInsensitiveComparisons) {
3714  0 sqlQuery = SQLConstants.GET_APPLICATIONS_COUNNT_CASESENSITVE_WITH_MULTIGROUPID;
3715    } else {
3716  0 sqlQuery = SQLConstants.GET_APPLICATIONS_COUNNT_NONE_CASESENSITVE_WITH_MULTIGROUPID;
3717    }
3718  0 String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
3719  0 String[] grpIdArray = groupingId.split(",");
3720  0 int noOfParams = grpIdArray.length;
3721  0 prepStmt = fillQueryParams(connection, sqlQuery, grpIdArray, 1);
3722  0 prepStmt.setString(++noOfParams, tenantDomain);
3723  0 prepStmt.setString(++noOfParams, subscriber.getName());
3724  0 prepStmt.setString(++noOfParams, "%" + search + "%");
3725    } else {
3726  0 if (forceCaseInsensitiveComparisons) {
3727  0 sqlQuery = SQLConstants.GET_APPLICATIONS_COUNNT_CASESENSITVE_WITHGROUPID;
3728    } else {
3729  0 sqlQuery = SQLConstants.GET_APPLICATIONS_COUNNT_NONE_CASESENSITVE_WITHGROUPID;
3730    }
3731  0 prepStmt = connection.prepareStatement(sqlQuery);
3732  0 prepStmt.setString(1, groupingId);
3733  0 prepStmt.setString(2, subscriber.getName());
3734  0 prepStmt.setString(3, "%" + search + "%");
3735    }
3736   
3737    } else {
3738   
3739  0 if (forceCaseInsensitiveComparisons) {
3740  0 sqlQuery = SQLConstants.GET_APPLICATIONS_COUNNT_CASESENSITVE;
3741    } else {
3742  0 sqlQuery = SQLConstants.GET_APPLICATIONS_COUNNT_NONE_CASESENSITVE;
3743    }
3744  0 prepStmt = connection.prepareStatement(sqlQuery);
3745  0 prepStmt.setString(1, subscriber.getName());
3746  0 prepStmt.setString(2, "%" + search + "%");
3747    }
3748   
3749  0 resultSet = prepStmt.executeQuery();
3750   
3751  0 int applicationCount = 0;
3752  0 if (resultSet != null) {
3753  0 while (resultSet.next()) {
3754  0 applicationCount = resultSet.getInt("count");
3755    }
3756    }
3757  0 if (applicationCount > 0) {
3758  0 return applicationCount;
3759    }
3760    } catch (SQLException e) {
3761  0 handleException("Failed to get applicaiton count : ", e);
3762    } finally {
3763  0 APIMgtDBUtil.closeAllConnections(prepStmt, connection, resultSet);
3764    }
3765   
3766  0 return 0;
3767    }
3768   
3769    /**
3770    * Returns all applications created by given user Id
3771    *
3772    * @param userId
3773    * @return
3774    * @throws APIManagementException
3775    */
 
3776  0 toggle public Application[] getApplicationsByOwner(String userId) throws APIManagementException {
3777   
3778  0 Connection connection = null;
3779  0 PreparedStatement prepStmt = null;
3780  0 ResultSet rs = null;
3781  0 String appName = null;
3782  0 Application[] applications = null;
3783   
3784  0 String sqlQuery = SQLConstants.GET_APPLICATIONS_BY_OWNER;
3785   
3786  0 try {
3787  0 connection = APIMgtDBUtil.getConnection();
3788  0 prepStmt = connection.prepareStatement(sqlQuery);
3789  0 prepStmt.setString(1, userId);
3790  0 rs = prepStmt.executeQuery();
3791   
3792  0 ArrayList<Application> applicationsList = new ArrayList<Application>();
3793  0 Application application;
3794  0 while (rs.next()) {
3795  0 application = new Application(rs.getString("UUID"));
3796  0 application.setName(rs.getString("NAME"));
3797  0 application.setOwner(rs.getString("CREATED_BY"));
3798  0 application.setStatus(rs.getString("APPLICATION_STATUS"));
3799  0 application.setGroupId(rs.getString("GROUP_ID"));
3800   
3801  0 if (multiGroupAppSharingEnabled) {
3802  0 application.setGroupId(getGroupId(rs.getInt("APPLICATION_ID")));
3803    }
3804  0 applicationsList.add(application);
3805    }
3806  0 applications = applicationsList.toArray(new Application[applicationsList.size()]);
3807    } catch (SQLException e) {
3808  0 handleException("Error when getting the application name for id " + userId, e);
3809    } finally {
3810  0 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
3811    }
3812  0 return applications;
3813    }
3814   
3815    /**
3816    * Returns all applications created by given user Id
3817    *
3818    * @param userName
3819    * @return
3820    * @throws APIManagementException
3821    */
 
3822  0 toggle public boolean updateApplicationOwner(String userName, Application application) throws
3823    APIManagementException {
3824   
3825  0 boolean isAppUpdated = false;
3826  0 Connection connection = null;
3827  0 PreparedStatement prepStmt = null;
3828  0 String appName = null;
3829   
3830  0 String sqlQuery = SQLConstants.UPDATE_APPLICATION_OWNER;
3831   
3832  0 try {
3833  0 Subscriber subscriber = getSubscriber(userName);
3834  0 if (subscriber != null) {
3835  0 int subscriberId = getSubscriber(userName).getId();
3836  0 connection = APIMgtDBUtil.getConnection();
3837  0 prepStmt = connection.prepareStatement(sqlQuery);
3838  0 prepStmt.setString(1, userName);
3839  0 prepStmt.setInt(2, subscriberId);
3840  0 prepStmt.setString(3, application.getUUID());
3841  0 prepStmt.executeUpdate();
3842  0 isAppUpdated = true;
3843    } else {
3844  0 String errorMessage = "Error when retrieving subscriber details for user " + userName;
3845  0 handleException(errorMessage, new APIManagementException(errorMessage));
3846    }
3847    } catch (SQLException e) {
3848  0 handleException("Error when updating application owner for user " + userName, e);
3849    } finally {
3850  0 APIMgtDBUtil.closeAllConnections(prepStmt, connection, null);
3851    }
3852  0 return isAppUpdated;
3853    }
3854   
3855    /**
3856    * #TODO later we might need to use only this method.
3857    *
3858    * @param subscriber The subscriber.
3859    * @param groupingId The groupId to which the applications must belong.
3860    * @param start The start index.
3861    * @param offset The offset.
3862    * @param search The search string.
3863    * @param sortOrder The sort order.
3864    * @param sortColumn The sort column.
3865    * @return Application[] The array of applications.
3866    * @throws APIManagementException
3867    */
 
3868  0 toggle public Application[] getApplicationsWithPagination(Subscriber subscriber, String groupingId, int start,
3869    int offset, String search, String sortColumn, String sortOrder)
3870    throws APIManagementException {
3871   
3872  0 Connection connection = null;
3873  0 PreparedStatement prepStmt = null;
3874  0 ResultSet rs = null;
3875  0 Application[] applications = null;
3876  0 String sqlQuery = null;
3877   
3878  0 if (groupingId != null && !"null".equals(groupingId) && !groupingId.isEmpty()) {
3879  0 if (multiGroupAppSharingEnabled) {
3880  0 if (forceCaseInsensitiveComparisons) {
3881  0 sqlQuery = SQLConstantManagerFactory.
3882    getSQlString("GET_APPLICATIONS_PREFIX_NONE_CASESENSITVE_WITH_MULTIGROUPID");
3883    } else {
3884  0 sqlQuery = SQLConstantManagerFactory.
3885    getSQlString("GET_APPLICATIONS_PREFIX_CASESENSITVE_WITH_MULTIGROUPID");
3886    }
3887    } else {
3888  0 if (forceCaseInsensitiveComparisons) {
3889  0 sqlQuery = SQLConstantManagerFactory.
3890    getSQlString("GET_APPLICATIONS_PREFIX_CASESENSITVE_WITHGROUPID");
3891    } else {
3892  0 sqlQuery = SQLConstantManagerFactory.
3893    getSQlString("GET_APPLICATIONS_PREFIX_NONE_CASESENSITVE_WITHGROUPID");
3894    }
3895    }
3896    } else {
3897  0 if (forceCaseInsensitiveComparisons) {
3898  0 sqlQuery = SQLConstantManagerFactory.getSQlString("GET_APPLICATIONS_PREFIX_CASESENSITVE");
3899    } else {
3900  0 sqlQuery = SQLConstantManagerFactory.getSQlString("GET_APPLICATIONS_PREFIX_NONE_CASESENSITVE");
3901    }
3902    }
3903   
3904  0 try {
3905  0 connection = APIMgtDBUtil.getConnection();
3906    // sortColumn, sortOrder variable values has sanitized in jaggery level (applications-list.jag)for security.
3907  0 sqlQuery = sqlQuery.replace("$1", sortColumn);
3908  0 sqlQuery = sqlQuery.replace("$2", sortOrder);
3909   
3910  0 if (groupingId != null && !"null".equals(groupingId) && !groupingId.isEmpty()) {
3911  0 if (multiGroupAppSharingEnabled) {
3912  0 String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
3913  0 String[] grpIdArray = groupingId.split(",");
3914  0 int noOfParams = grpIdArray.length;
3915  0 prepStmt = fillQueryParams(connection, sqlQuery, grpIdArray, 1);
3916  0 prepStmt.setString(++noOfParams, tenantDomain);
3917  0 prepStmt.setString(++noOfParams, subscriber.getName());
3918  0 prepStmt.setString(++noOfParams, tenantDomain + '/' + groupingId);
3919  0 prepStmt.setString(++noOfParams, "%" + search + "%");
3920  0 prepStmt.setInt(++noOfParams, start);
3921  0 prepStmt.setInt(++noOfParams, offset);
3922    } else {
3923  0 prepStmt = connection.prepareStatement(sqlQuery);
3924  0 prepStmt.setString(1, groupingId);
3925  0 prepStmt.setString(2, subscriber.getName());
3926  0 prepStmt.setString(3, "%" + search + "%");
3927  0 prepStmt.setInt(4, start);
3928  0 prepStmt.setInt(5, offset);
3929    }
3930    } else {
3931  0 prepStmt = connection.prepareStatement(sqlQuery);
3932  0 prepStmt.setString(1, subscriber.getName());
3933  0 prepStmt.setString(2, "%" + search + "%");
3934  0 prepStmt.setInt(3, start);
3935  0 prepStmt.setInt(4, offset);
3936    }
3937  0 rs = prepStmt.executeQuery();
3938  0 ArrayList<Application> applicationsList = new ArrayList<Application>();
3939  0 Application application;
3940  0 while (rs.next()) {
3941  0 application = new Application(rs.getString("NAME"), subscriber);
3942  0 application.setId(rs.getInt("APPLICATION_ID"));
3943  0 application.setTier(rs.getString("APPLICATION_TIER"));
3944  0 application.setDescription(rs.getString("DESCRIPTION"));
3945  0 application.setStatus(rs.getString("APPLICATION_STATUS"));
3946  0 application.setGroupId(rs.getString("GROUP_ID"));
3947  0 application.setUUID(rs.getString("UUID"));
3948  0 application.setIsBlackListed(rs.getBoolean("ENABLED"));
3949  0 application.setOwner(rs.getString("CREATED_BY"));
3950   
3951  0 if (multiGroupAppSharingEnabled) {
3952  0 setGroupIdInApplication(application);
3953    }
3954   
3955  0 applicationsList.add(application);
3956    }
3957   
3958  0 applications = applicationsList.toArray(new Application[applicationsList.size()]);
3959    } catch (SQLException e) {
3960  0 handleException("Error when reading the application information from" + " the persistence store.", e);
3961    } finally {
3962  0 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
3963    }
3964  0 return applications;
3965    }
3966   
3967    /**
3968    * Returns all the applications associated with given subscriber and group id.
3969    *
3970    * @param subscriber The subscriber.
3971    * @param groupingId The groupId to which the applications must belong.
3972    * @return Application[] Array of applications.
3973    * @throws APIManagementException
3974    */
 
3975  162 toggle public Application[] getApplications(Subscriber subscriber, String groupingId) throws APIManagementException {
3976   
3977  162 Application[] applications = getLightWeightApplications(subscriber, groupingId);
3978   
3979  162 for (Application application : applications) {
3980   
3981  235 Map<String, OAuthApplicationInfo> keyMap = getOAuthApplications(application.getId());
3982   
3983  235 for (Map.Entry<String, OAuthApplicationInfo> entry : keyMap.entrySet()) {
3984  175 application.addOAuthApp(entry.getKey(), entry.getValue());
3985    }
3986   
3987    }
3988  162 return applications;
3989    }
3990   
3991    /**
3992    * Returns all the applications associated with given subscriber and group id, without their keys.
3993    *
3994    * @param subscriber The subscriber.
3995    * @param groupingId The groupId to which the applications must belong.
3996    * @return Application[] Array of applications.
3997    * @throws APIManagementException
3998    */
 
3999  461 toggle public Application[] getLightWeightApplications(Subscriber subscriber, String groupingId) throws
4000    APIManagementException {
4001   
4002  461 Connection connection = null;
4003  461 PreparedStatement prepStmt = null;
4004  461 ResultSet rs = null;
4005  461 Application[] applications = null;
4006  461 String sqlQuery = SQLConstants.GET_APPLICATIONS_PREFIX;
4007   
4008  461 String whereClauseWithGroupId;
4009  461 String whereClauseWithMultiGroupId;
4010   
4011  461 if (forceCaseInsensitiveComparisons) {
4012  461 if (multiGroupAppSharingEnabled) {
4013  0 whereClauseWithGroupId = " AND ( (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM " +
4014    "AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?)) " +
4015    "OR (LOWER(SUB.USER_ID) = LOWER(?))" +
4016    "OR (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM AM_APPLICATION WHERE GROUP_ID = ?)))";
4017    } else {
4018  461 whereClauseWithGroupId = " AND " + " (GROUP_ID= ? " + " OR "
4019    + " ((GROUP_ID='' OR GROUP_ID IS NULL) AND LOWER(SUB.USER_ID) = LOWER(?))) ";
4020    }
4021    } else {
4022  0 if (multiGroupAppSharingEnabled) {
4023  0 whereClauseWithGroupId = " AND ( (APP.APPLICATION_ID IN (SELECT APPLICATION_ID " +
4024    "FROM AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?)) " +
4025    "OR ( SUB.USER_ID = ? )" +
4026    "OR (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM AM_APPLICATION WHERE GROUP_ID = ?))) ";
4027    } else {
4028  0 whereClauseWithGroupId = " AND " + " (GROUP_ID= ? " + " OR "
4029    + " ((GROUP_ID='' OR GROUP_ID IS NULL) AND SUB.USER_ID=?))";
4030    }
4031    }
4032   
4033  461 String whereClause;
4034  461 if (forceCaseInsensitiveComparisons) {
4035  461 whereClause = " AND " + " LOWER(SUB.USER_ID) = LOWER(?)";
4036    } else {
4037  0 whereClause = " AND " + " SUB.USER_ID = ?";
4038    }
4039   
4040  461 if (groupingId != null && !"null".equals(groupingId) && !groupingId.isEmpty()) {
4041  0 sqlQuery += whereClauseWithGroupId;
4042    } else {
4043  461 sqlQuery += whereClause;
4044    }
4045  461 try {
4046  461 connection = APIMgtDBUtil.getConnection();
4047  461 String blockingFilerSql = null;
4048  461 if (connection.getMetaData().getDriverName().contains("MS SQL") ||
4049    connection.getMetaData().getDriverName().contains("Microsoft")) {
4050  0 sqlQuery = sqlQuery.replaceAll("NAME", "cast(NAME as varchar(100)) collate " +
4051    "SQL_Latin1_General_CP1_CI_AS as NAME");
4052  0 blockingFilerSql = " select distinct x.*,bl.ENABLED from ( " + sqlQuery + " )x left join " +
4053    "AM_BLOCK_CONDITIONS bl on ( bl.TYPE = 'APPLICATION' AND bl.VALUE = (x.USER_ID + ':') + x" +
4054    ".name)";
4055    } else {
4056  461 blockingFilerSql = " select distinct x.*,bl.ENABLED from ( " + sqlQuery
4057    + " )x left join AM_BLOCK_CONDITIONS bl on ( bl.TYPE = 'APPLICATION' AND bl.VALUE = "
4058    + "concat(concat(x.USER_ID,':'),x.name))";
4059    }
4060   
4061  461 if (groupingId != null && !"null".equals(groupingId) && !groupingId.isEmpty()) {
4062  0 if (multiGroupAppSharingEnabled) {
4063  0 String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
4064  0 String groupIDArray[] = groupingId.split(",");
4065  0 int paramIndex = groupIDArray.length;
4066  0 prepStmt = fillQueryParams(connection, blockingFilerSql, groupIDArray, 1);
4067  0 prepStmt.setString(++paramIndex, tenantDomain);
4068  0 prepStmt.setString(++paramIndex, subscriber.getName());
4069  0 prepStmt.setString(++paramIndex, tenantDomain + '/' + groupingId);
4070    } else {
4071  0 prepStmt = connection.prepareStatement(blockingFilerSql);
4072  0 prepStmt.setString(1, groupingId);
4073  0 prepStmt.setString(2, subscriber.getName());
4074    }
4075    } else {
4076  461 prepStmt = connection.prepareStatement(blockingFilerSql);
4077  461 prepStmt.setString(1, subscriber.getName());
4078    }
4079  461 rs = prepStmt.executeQuery();
4080  461 ArrayList<Application> applicationsList = new ArrayList<Application>();
4081  461 Application application;
4082  461 Map<String,String> applicationAttributes;
4083  461 int applicationId = 0;
4084  1294 while (rs.next()) {
4085  833 applicationId = rs.getInt("APPLICATION_ID");
4086  833 application = new Application(rs.getString("NAME"), subscriber);
4087  833 application.setId(applicationId);
4088  833 application.setTier(rs.getString("APPLICATION_TIER"));
4089  833 application.setCallbackUrl(rs.getString("CALLBACK_URL"));
4090  833 application.setDescription(rs.getString("DESCRIPTION"));
4091  833 application.setStatus(rs.getString("APPLICATION_STATUS"));
4092  833 application.setGroupId(rs.getString("GROUP_ID"));
4093  833 application.setUUID(rs.getString("UUID"));
4094  833 application.setIsBlackListed(rs.getBoolean("ENABLED"));
4095  833 application.setOwner(rs.getString("CREATED_BY"));
4096  833 application.setTokenType(rs.getString("TOKEN_TYPE"));
4097  833 applicationAttributes = getApplicationAttributes(connection, applicationId);
4098  833 application.setApplicationAttributes(applicationAttributes);
4099  833 if (multiGroupAppSharingEnabled) {
4100  0 setGroupIdInApplication(application);
4101    }
4102  833 applicationsList.add(application);
4103    }
4104  461 Collections.sort(applicationsList, new Comparator<Application>() {
 
4105  535 toggle public int compare(Application o1, Application o2) {
4106  535 return o1.getName().compareToIgnoreCase(o2.getName());
4107    }
4108    });
4109  461 applications = applicationsList.toArray(new Application[applicationsList.size()]);
4110    } catch (SQLException e) {
4111  0 handleException("Error when reading the application information from" + " the persistence store.", e);
4112    } finally {
4113  461 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
4114    }
4115  461 return applications;
4116    }
4117   
 
4118  0 toggle public Application[] getAllApplicationsOfTenantForMigration(String appTenantDomain) throws
4119    APIManagementException {
4120   
4121  0 Connection connection;
4122  0 PreparedStatement prepStmt = null;
4123  0 ResultSet rs;
4124  0 Application[] applications = null;
4125  0 String sqlQuery = SQLConstants.GET_SIMPLE_APPLICATIONS;
4126   
4127  0 String tenantFilter = "AND SUB.TENANT_ID=?";
4128  0 sqlQuery += tenantFilter ;
4129  0 try {
4130  0 connection = APIMgtDBUtil.getConnection();
4131   
4132  0 int appTenantId = APIUtil.getTenantIdFromTenantDomain(appTenantDomain);
4133  0 prepStmt = connection.prepareStatement(sqlQuery);
4134  0 prepStmt.setInt(1, appTenantId);
4135  0 rs = prepStmt.executeQuery();
4136   
4137  0 ArrayList<Application> applicationsList = new ArrayList<Application>();
4138  0 Application application;
4139  0 while (rs.next()) {
4140  0 application = new Application(Integer.parseInt(rs.getString("APPLICATION_ID")));
4141  0 application.setName(rs.getString("NAME"));
4142  0 application.setOwner(rs.getString("CREATED_BY"));
4143  0 applicationsList.add(application);
4144    }
4145  0 applications = applicationsList.toArray(new Application[applicationsList.size()]);
4146    } catch (SQLException e) {
4147  0 handleException("Error when reading the application information from" + " the persistence store.", e);
4148    } finally {
4149  0 if (prepStmt != null) {
4150  0 try {
4151  0 prepStmt.close();
4152    } catch (SQLException e) {
4153  0 log.warn("Database error. Could not close Statement. Continuing with others." + e.getMessage(), e);
4154    }
4155    }
4156    }
4157  0 return applications;
4158    }
4159   
4160    /**
4161    * Returns all the consumerkeys of application which are subscribed for the given api
4162    *
4163    * @param identifier APIIdentifier
4164    * @return Consumerkeys
4165    * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to get Applications for given subscriber.
4166    */
 
4167  0 toggle public String[] getConsumerKeys(APIIdentifier identifier) throws APIManagementException {
4168   
4169  0 Set<String> consumerKeys = new HashSet<String>();
4170   
4171  0 Connection connection = null;
4172  0 PreparedStatement prepStmt = null;
4173  0 ResultSet rs = null;
4174   
4175  0 int apiId;
4176  0 String sqlQuery = SQLConstants.GET_CONSUMER_KEYS_SQL;
4177   
4178  0 try {
4179   
4180  0 connection = APIMgtDBUtil.getConnection();
4181  0 apiId = getAPIID(identifier, connection);
4182   
4183  0 prepStmt = connection.prepareStatement(sqlQuery);
4184  0 prepStmt.setInt(1, apiId);
4185  0 rs = prepStmt.executeQuery();
4186   
4187  0 while (rs.next()) {
4188  0 consumerKeys.add(rs.getString("CONSUMER_KEY"));
4189    }
4190   
4191    } catch (SQLException e) {
4192  0 handleException("Error when reading application subscription information", e);
4193    } finally {
4194  0 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
4195    }
4196   
4197  0 return consumerKeys.toArray(new String[consumerKeys.size()]);
4198    }
4199   
4200    /**
4201    * Deletes an Application along with subscriptions, keys and registration data
4202    *
4203    * @param application Application object to be deleted from the database which has the application Id
4204    * @throws APIManagementException
4205    */
 
4206  130 toggle public void deleteApplication(Application application) throws APIManagementException {
4207  130 Connection connection = null;
4208  130 PreparedStatement deleteMappingQuery = null;
4209  130 PreparedStatement prepStmt = null;
4210  130 PreparedStatement prepStmtGetConsumerKey = null;
4211  130 PreparedStatement deleteRegistrationQuery = null;
4212  130 PreparedStatement deleteSubscription = null;
4213  130 PreparedStatement deleteDomainApp = null;
4214  130 PreparedStatement deleteAppKey = null;
4215  130 PreparedStatement deleteApp = null;
4216  130 ResultSet rs = null;
4217   
4218  130 String getSubscriptionsQuery = SQLConstants.GET_SUBSCRIPTION_ID_OF_APPLICATION_SQL;
4219   
4220  130 String getConsumerKeyQuery = SQLConstants.GET_CONSUMER_KEY_OF_APPLICATION_SQL;
4221   
4222  130 String deleteKeyMappingQuery = SQLConstants.REMOVE_APPLICATION_FROM_SUBSCRIPTION_KEY_MAPPINGS_SQL;
4223  130 String deleteSubscriptionsQuery = SQLConstants.REMOVE_APPLICATION_FROM_SUBSCRIPTIONS_SQL;
4224  130 String deleteApplicationKeyQuery = SQLConstants.REMOVE_APPLICATION_FROM_APPLICATION_KEY_MAPPINGS_SQL;
4225  130 String deleteDomainAppQuery = SQLConstants.REMOVE_APPLICATION_FROM_DOMAIN_MAPPINGS_SQL;
4226  130 String deleteApplicationQuery = SQLConstants.REMOVE_APPLICATION_FROM_APPLICATIONS_SQL;
4227  130 String deleteRegistrationEntry = SQLConstants.REMOVE_APPLICATION_FROM_APPLICATION_REGISTRATIONS_SQL;
4228   
4229  130 boolean transactionCompleted = true;
4230  130 try {
4231  130 connection = APIMgtDBUtil.getConnection();
4232  130 connection.setAutoCommit(false);
4233  130 prepStmt = connection.prepareStatement(getSubscriptionsQuery);
4234  130 prepStmt.setInt(1, application.getId());
4235  130 rs = prepStmt.executeQuery();
4236   
4237  130 if (multiGroupAppSharingEnabled) {
4238  0 transactionCompleted = updateGroupIDMappings(connection, application.getId(), null, null);
4239    }
4240   
4241  130 List<Integer> subscriptions = new ArrayList<Integer>();
4242  185 while (rs.next()) {
4243  55 subscriptions.add(rs.getInt("SUBSCRIPTION_ID"));
4244    }
4245   
4246  130 deleteMappingQuery = connection.prepareStatement(deleteKeyMappingQuery);
4247  130 for (Integer subscriptionId : subscriptions) {
4248  55 deleteMappingQuery.setInt(1, subscriptionId);
4249  55 deleteMappingQuery.addBatch();
4250    }
4251  130 deleteMappingQuery.executeBatch();
4252   
4253  130 if (log.isDebugEnabled()) {
4254  10 log.debug("Subscription Key mapping details are deleted successfully for Application - " +
4255    application.getName());
4256    }
4257   
4258  130 deleteRegistrationQuery = connection.prepareStatement(deleteRegistrationEntry);
4259  130 deleteRegistrationQuery.setInt(1, application.getId());
4260  130 deleteRegistrationQuery.execute();
4261   
4262  130 if (log.isDebugEnabled()) {
4263  10 log.debug("Application Registration details are deleted successfully for Application - " +
4264    application.getName());
4265    }
4266   
4267  130 deleteSubscription = connection.prepareStatement(deleteSubscriptionsQuery);
4268  130 deleteSubscription.setInt(1, application.getId());
4269  130 deleteSubscription.execute();
4270   
4271  130 if (log.isDebugEnabled()) {
4272  10 log.debug("Subscription details are deleted successfully for Application - " + application.getName());
4273    }
4274   
4275  130 prepStmtGetConsumerKey = connection.prepareStatement(getConsumerKeyQuery);
4276  130 prepStmtGetConsumerKey.setInt(1, application.getId());
4277  130 rs = prepStmtGetConsumerKey.executeQuery();
4278  130 ArrayList<String> consumerKeys = new ArrayList<String>();
4279   
4280  130 deleteDomainApp = connection.prepareStatement(deleteDomainAppQuery);
4281  230 while (rs.next()) {
4282  100 String consumerKey = rs.getString("CONSUMER_KEY");
4283   
4284    // This is true when OAuth app has been created by pasting consumer key/secret in the screen.
4285  100 String mode = rs.getString("CREATE_MODE");
4286  100 if (consumerKey != null) {
4287  100 deleteDomainApp.setString(1, consumerKey);
4288  100 deleteDomainApp.addBatch();
4289   
4290  100 KeyManagerHolder.getKeyManagerInstance().deleteMappedApplication(consumerKey);
4291    // OAuth app is deleted if only it has been created from API Store. For mapped clients we don't
4292    // call delete.
4293  100 if (!"MAPPED".equals(mode)) {
4294    // Adding clients to be deleted.
4295  100 consumerKeys.add(consumerKey);
4296    }
4297   
4298    }
4299    }
4300  130 deleteDomainApp.executeBatch();
4301   
4302  130 deleteAppKey = connection.prepareStatement(deleteApplicationKeyQuery);
4303  130 deleteAppKey.setInt(1, application.getId());
4304  130 deleteAppKey.execute();
4305   
4306  130 if (log.isDebugEnabled()) {
4307  10 log.debug("Application Key Mapping details are deleted successfully for Application - " + application
4308    .getName());
4309    }
4310   
4311  130 deleteApp = connection.prepareStatement(deleteApplicationQuery);
4312  130 deleteApp.setInt(1, application.getId());
4313  130 deleteApp.execute();
4314   
4315  130 if (log.isDebugEnabled()) {
4316  10 log.debug("Application " + application.getName() + " is deleted successfully.");
4317    }
4318   
4319  130 if (transactionCompleted) {
4320  130 connection.commit();
4321    }
4322   
4323  130 for (String consumerKey : consumerKeys) {
4324    //delete on oAuthorization server.
4325  100 KeyManagerHolder.getKeyManagerInstance().deleteApplication(consumerKey);
4326    }
4327    } catch (SQLException e) {
4328  0 handleException("Error while removing application details from the database", e);
4329    } finally {
4330  130 APIMgtDBUtil.closeAllConnections(prepStmtGetConsumerKey, connection, rs);
4331  130 APIMgtDBUtil.closeAllConnections(prepStmt, null, rs);
4332  130 APIMgtDBUtil.closeAllConnections(deleteApp, null, null);
4333  130 APIMgtDBUtil.closeAllConnections(deleteAppKey, null, null);
4334  130 APIMgtDBUtil.closeAllConnections(deleteMappingQuery, null, null);
4335  130 APIMgtDBUtil.closeAllConnections(deleteRegistrationQuery, null, null);
4336  130 APIMgtDBUtil.closeAllConnections(deleteSubscription, null, null);
4337  130 APIMgtDBUtil.closeAllConnections(deleteDomainApp, null, null);
4338  130 APIMgtDBUtil.closeAllConnections(deleteAppKey, null, null);
4339  130 APIMgtDBUtil.closeAllConnections(deleteApp, null, null);
4340   
4341    }
4342    }
4343   
 
4344  0 toggle public APIKey[] getConsumerKeysWithMode(int appId, String mode) throws APIManagementException {
4345   
4346  0 Connection connection = null;
4347  0 PreparedStatement prepStmt = null;
4348  0 ResultSet rs = null;
4349  0 ArrayList<APIKey> consumerKeys = new ArrayList<APIKey>();
4350   
4351  0 String getConsumerKeyQuery = SQLConstants.GET_CONSUMER_KEY_WITH_MODE_SLQ;
4352   
4353  0 try {
4354  0 connection = APIMgtDBUtil.getConnection();
4355  0 connection.setAutoCommit(false);
4356  0 prepStmt = connection.prepareStatement(getConsumerKeyQuery);
4357  0 prepStmt.setInt(1, appId);
4358  0 prepStmt.setString(2, mode);
4359  0 rs = prepStmt.executeQuery();
4360  0 while (rs.next()) {
4361  0 String consumerKey = rs.getString("CONSUMER_KEY");
4362   
4363  0 if (consumerKey != null && !consumerKey.isEmpty()) {
4364  0 APIKey apiKey = new APIKey();
4365  0 apiKey.setConsumerKey(consumerKey);
4366  0 apiKey.setType(rs.getString("KEY_TYPE"));
4367  0 consumerKeys.add(apiKey);
4368    }
4369    }
4370    } catch (SQLException e) {
4371  0 String msg = "Error occurred while getting consumer keys";
4372  0 log.error(msg, e);
4373  0 throw new APIManagementException(msg, e);
4374    } finally {
4375  0 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
4376    }
4377  0 return consumerKeys.toArray(new APIKey[consumerKeys.size()]);
4378    }
4379   
4380    /**
4381    * Returns the consumer Key for a given Application Name, Subscriber Name, Key Type, Grouping Id combination.
4382    *
4383    * @param applicationName Name of the Application.
4384    * @param subscriberId Name of Subscriber.
4385    * @param keyType PRODUCTION | SANDBOX.
4386    * @param groupingId Grouping ID. When set to null query will be performed using the other three values.
4387    * @return Consumer Key matching the provided combination.
4388    * @throws APIManagementException
4389    */
 
4390  9 toggle public String getConsumerKeyForApplicationKeyType(String applicationName, String subscriberId, String keyType,
4391    String groupingId) throws APIManagementException {
4392   
4393  9 String consumerKey = null;
4394  9 Connection connection = null;
4395  9 PreparedStatement prepStmt = null;
4396  9 ResultSet rs = null;
4397  9 String sqlQuery = SQLConstants.GET_CONSUMER_KEY_FOR_APPLICATION_KEY_TYPE_SQL;
4398  9 String whereSubscriberUserID = "SUB.USER_ID = ?";
4399   
4400  9 if (forceCaseInsensitiveComparisons) {
4401  9 whereSubscriberUserID = "lower(SUB.USER_ID) = ?";
4402  9 subscriberId = subscriberId.toLowerCase();
4403    }
4404   
4405  9 String whereClauseWithGroupId = " AND " + "(APP.GROUP_ID= ? OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL) AND " +
4406    whereSubscriberUserID + "))";
4407   
4408  9 String whereClauseWithMultiGroupId = " AND ( (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM " +
4409    "AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?)) OR " +
4410    whereSubscriberUserID + ")";
4411   
4412  9 String whereClause = " AND " + whereSubscriberUserID;
4413  9 try {
4414  9 connection = APIMgtDBUtil.getConnection();
4415   
4416  9 if (groupingId != null && !"null".equals(groupingId) && !groupingId.isEmpty()) {
4417  0 if (multiGroupAppSharingEnabled) {
4418  0 Subscriber subscriber = getSubscriber(subscriberId);
4419  0 String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
4420  0 String groupIDArray[] = groupingId.split(",");
4421  0 sqlQuery += whereClauseWithMultiGroupId;
4422  0 prepStmt = fillQueryParams(connection, sqlQuery, groupIDArray, 3);
4423  0 prepStmt.setString(1, applicationName);
4424  0 prepStmt.setString(2, keyType);
4425  0 int paramIndex = groupIDArray.length + 2;
4426  0 prepStmt.setString(++paramIndex, tenantDomain);
4427  0 prepStmt.setString(++paramIndex, subscriberId);
4428    } else {
4429  0 sqlQuery += whereClauseWithGroupId;
4430  0 prepStmt = connection.prepareStatement(sqlQuery);
4431  0 prepStmt.setString(1, applicationName);
4432  0 prepStmt.setString(2, keyType);
4433  0 prepStmt.setString(3, groupingId);
4434  0 prepStmt.setString(4, subscriberId);
4435    }
4436    } else {
4437  9 sqlQuery += whereClause;
4438  9 prepStmt = connection.prepareStatement(sqlQuery);
4439  9 prepStmt.setString(1, applicationName);
4440  9 prepStmt.setString(2, keyType);
4441  9 prepStmt.setString(3, subscriberId);
4442    }
4443   
4444  9 rs = prepStmt.executeQuery();
4445   
4446  18 while (rs.next()) {
4447  9 consumerKey = rs.getString("CONSUMER_KEY");
4448    }
4449    } catch (SQLException e) {
4450  0 handleException("Error when reading the application information from" + " the persistence store.", e);
4451    } finally {
4452  9 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
4453    }
4454  9 return consumerKey;
4455    }
4456   
4457    /**
4458    * This method will return a java Map that contains application ID and token type.
4459    *
4460    * @param consumerKey consumer key of the oAuth application.
4461    * @return Map.
4462    * @throws APIManagementException
4463    */
 
4464  0 toggle public Map<String, String> getApplicationIdAndTokenTypeByConsumerKey(String consumerKey)
4465    throws APIManagementException {
4466  0 Map<String, String> appIdAndConsumerKey = new HashMap<String, String>();
4467   
4468  0 if (log.isDebugEnabled()) {
4469  0 log.debug("fetching application id and token type by consumer key " + consumerKey);
4470    }
4471   
4472  0 Connection connection = null;
4473  0 PreparedStatement prepStmt = null;
4474  0 ResultSet rs = null;
4475   
4476  0 String sqlQuery = SQLConstants.GET_APPLICATION_ID_BY_CONSUMER_KEY_SQL;
4477  0 try {
4478  0 connection = APIMgtDBUtil.getConnection();
4479   
4480  0 prepStmt = connection.prepareStatement(sqlQuery);
4481  0 prepStmt.setString(1, consumerKey);
4482  0 rs = prepStmt.executeQuery();
4483  0 while (rs.next()) {
4484  0 appIdAndConsumerKey.put("application_id", rs.getString("APPLICATION_ID"));
4485  0 appIdAndConsumerKey.put("token_type", rs.getString("KEY_TYPE"));
4486    }
4487    } catch (SQLException e) {
4488  0 handleException("Error when reading application subscription information", e);
4489    } finally {
4490  0 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
4491    }
4492  0 return appIdAndConsumerKey;
4493    }
4494   
4495    /*
4496    Delete mapping record by given consumer key
4497    */
 
4498  0 toggle public void deleteApplicationKeyMappingByConsumerKey(String consumerKey) throws APIManagementException {
4499   
4500  0 Connection connection = null;
4501  0 PreparedStatement ps = null;
4502  0 try {
4503  0 connection = APIMgtDBUtil.getConnection();
4504  0 connection.setAutoCommit(false);
4505  0 String deleteKeyMappingQuery = SQLConstants.DELETE_APPLICATION_KEY_MAPPING_BY_CONSUMER_KEY_SQL;
4506  0 if (log.isDebugEnabled()) {
4507  0 log.debug("trying to delete key mapping for consumer id " + consumerKey);
4508    }
4509  0 ps = connection.prepareStatement(deleteKeyMappingQuery);
4510  0 ps.setString(1, consumerKey);
4511  0 ps.executeUpdate();
4512  0 connection.commit();
4513    } catch (SQLException e) {
4514  0 handleException("Error while removing application mapping table", e);
4515    } finally {
4516  0 APIMgtDBUtil.closeAllConnections(ps, connection, null);
4517    }
4518    }
4519   
4520    /**
4521    * This method will delete a record from AM_APPLICATION_REGISTRATION
4522    *
4523    * @param applicationId
4524    * @param tokenType
4525    */
 
4526  0 toggle public void deleteApplicationKeyMappingByApplicationIdAndType(String applicationId, String tokenType)
4527    throws APIManagementException {
4528   
4529  0 Connection connection = null;
4530  0 PreparedStatement ps = null;
4531  0 try {
4532  0 connection = APIMgtDBUtil.getConnection();
4533  0 connection.setAutoCommit(false);
4534  0 String deleteRegistrationEntry = SQLConstants.DELETE_APPLICATION_KEY_MAPPING_BY_APPLICATION_ID_SQL;
4535   
4536  0 if (log.isDebugEnabled()) {
4537  0 log.debug("trying to delete a record from AM_APPLICATION_KEY_MAPPING table by application ID " +
4538    applicationId + " and Token type" + tokenType);
4539    }
4540  0 ps = connection.prepareStatement(deleteRegistrationEntry);
4541  0 ps.setInt(1, Integer.parseInt(applicationId));
4542  0 ps.setString(2, tokenType);
4543  0 ps.executeUpdate();
4544  0 connection.commit();
4545    } catch (SQLException e) {
4546  0 handleException("Error while removing AM_APPLICATION_KEY_MAPPING table", e);
4547    } finally {
4548  0 APIMgtDBUtil.closeAllConnections(ps, connection, null);
4549    }
4550    }
4551   
4552    /**
4553    * Delete a record from AM_APPLICATION_REGISTRATION table by application ID and token type.
4554    *
4555    * @param applicationId APIM application ID.
4556    * @param tokenType Token type (PRODUCTION || SANDBOX)
4557    * @throws APIManagementException if failed to delete the record.
4558    */
 
4559  0 toggle public void deleteApplicationRegistration(String applicationId, String tokenType) throws APIManagementException {
4560   
4561  0 Connection connection = null;
4562  0 PreparedStatement ps = null;
4563  0 try {
4564  0 connection = APIMgtDBUtil.getConnection();
4565  0 connection.setAutoCommit(false);
4566  0 String deleteRegistrationEntry = SQLConstants.REMOVE_FROM_APPLICATION_REGISTRANTS_SQL;
4567   
4568  0 if (log.isDebugEnabled()) {
4569  0 log.debug("trying to delete a record from AM_APPLICATION_REGISTRATION table by application ID " +
4570    applicationId + " and Token type" + tokenType);
4571    }
4572  0 ps = connection.prepareStatement(deleteRegistrationEntry);
4573  0 ps.setInt(1, Integer.parseInt(applicationId));
4574  0 ps.setString(2, tokenType);
4575  0 ps.executeUpdate();
4576  0 connection.commit();
4577    } catch (SQLException e) {
4578  0 handleException("Error while removing AM_APPLICATION_REGISTRATION table", e);
4579    } finally {
4580  0 APIMgtDBUtil.closeAllConnections(ps, connection, null);
4581    }
4582    }
4583   
4584    /**
4585    * returns a subscriber record for given username,tenant Id
4586    *
4587    * @param username UserName
4588    * @param tenantId Tenant Id
4589    * @param connection
4590    * @return Subscriber
4591    * @throws APIManagementException if failed to get subscriber
4592    */
 
4593  178 toggle private Subscriber getSubscriber(String username, int tenantId, Connection connection)
4594    throws APIManagementException {
4595  178 PreparedStatement prepStmt = null;
4596  178 ResultSet rs = null;
4597  178 Subscriber subscriber = null;
4598  178 String sqlQuery;
4599   
4600  178 if (forceCaseInsensitiveComparisons) {
4601  178 sqlQuery = SQLConstants.GET_SUBSCRIBER_CASE_INSENSITIVE_SQL;
4602    } else {
4603  0 sqlQuery = SQLConstants.GET_SUBSCRIBER_DETAILS_SQL;
4604    }
4605   
4606  178 try {
4607  178 prepStmt = connection.prepareStatement(sqlQuery);
4608  178 prepStmt.setString(1, username);
4609  178 prepStmt.setInt(2, tenantId);
4610  178 rs = prepStmt.executeQuery();
4611   
4612  178 if (rs.next()) {
4613  178 subscriber = new Subscriber(rs.getString("USER_ID"));
4614  178 subscriber.setEmail(rs.getString("EMAIL_ADDRESS"));
4615  178 subscriber.setId(rs.getInt("SUBSCRIBER_ID"));
4616  178 subscriber.setSubscribedDate(rs.getDate("DATE_SUBSCRIBED"));
4617  178 subscriber.setTenantId(rs.getInt("TENANT_ID"));
4618  178 return subscriber;
4619    }
4620    } catch (SQLException e) {
4621  0 handleException("Error when reading the application information from" + " the persistence store.", e);
4622    } finally {
4623  178 APIMgtDBUtil.closeAllConnections(prepStmt, null, rs);
4624    }
4625  0 return subscriber;
4626    }
4627   
 
4628  0 toggle public void recordAPILifeCycleEvent(APIIdentifier identifier, APIStatus oldStatus, APIStatus newStatus,
4629    String userId, int tenantId) throws APIManagementException {
4630  0 Connection conn = null;
4631  0 try {
4632  0 conn = APIMgtDBUtil.getConnection();
4633  0 recordAPILifeCycleEvent(identifier, oldStatus.toString(), newStatus.toString(), userId, tenantId, conn);
4634    } catch (SQLException e) {
4635  0 handleException("Failed to record API state change", e);
4636    } finally {
4637  0 APIMgtDBUtil.closeAllConnections(null, conn, null);
4638    }
4639    }
4640   
 
4641  217 toggle public void recordAPILifeCycleEvent(APIIdentifier identifier, String oldStatus, String newStatus, String userId,
4642    int tenantId) throws APIManagementException {
4643  217 Connection conn = null;
4644  217 try {
4645  217 conn = APIMgtDBUtil.getConnection();
4646  217 recordAPILifeCycleEvent(identifier, oldStatus, newStatus, userId, tenantId, conn);
4647    } catch (SQLException e) {
4648  0 handleException("Failed to record API state change", e);
4649    } finally {
4650  217 APIMgtDBUtil.closeAllConnections(null, conn, null);
4651    }
4652    }
4653   
 
4654  487 toggle public void recordAPILifeCycleEvent(APIIdentifier identifier, String oldStatus, String newStatus, String userId,
4655    int tenantId, Connection conn) throws APIManagementException {
4656    //Connection conn = null;
4657  487 ResultSet resultSet = null;
4658  487 PreparedStatement ps = null;
4659  487 PreparedStatement selectQuerySt = null;
4660   
4661  487 int apiId = -1;
4662   
4663  487 if (oldStatus == null && !newStatus.equals(APIConstants.CREATED)) {
4664  0 String msg = "Invalid old and new state combination";
4665  0 log.error(msg);
4666  0 throw new APIManagementException(msg);
4667  487 } else if (oldStatus != null && oldStatus.equals(newStatus)) {
4668  0 String msg = "No measurable differences in API state";
4669  0 log.error(msg);
4670  0 throw new APIManagementException(msg);
4671    }
4672   
4673  487 String getAPIQuery = SQLConstants.GET_API_ID_SQL;
4674  487 String sqlQuery = SQLConstants.ADD_API_LIFECYCLE_EVENT_SQL;
4675  487 try {
4676  487 conn.setAutoCommit(false);
4677   
4678  487 selectQuerySt = conn.prepareStatement(getAPIQuery);
4679  487 selectQuerySt.setString(1, APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
4680  487 selectQuerySt.setString(2, identifier.getApiName());
4681  487 selectQuerySt.setString(3, identifier.getVersion());
4682  487 resultSet = selectQuerySt.executeQuery();
4683  487 if (resultSet.next()) {
4684  487 apiId = resultSet.getInt("API_ID");
4685    }
4686   
4687  487 if (apiId == -1) {
4688  0 String msg = "Unable to find the API: " + identifier + " in the database";
4689  0 log.error(msg);
4690  0 throw new APIManagementException(msg);
4691    }
4692   
4693  487 ps = conn.prepareStatement(sqlQuery);
4694  487 ps.setInt(1, apiId);
4695  487 if (oldStatus != null) {
4696  217 ps.setString(2, oldStatus);
4697    } else {
4698  270 ps.setNull(2, Types.VARCHAR);
4699    }
4700  487 ps.setString(3, newStatus);
4701  487 ps.setString(4, userId);
4702  487 ps.setInt(5, tenantId);
4703  487 ps.setTimestamp(6, new Timestamp(System.currentTimeMillis()));
4704   
4705  487 ps.executeUpdate();
4706   
4707    // finally commit transaction
4708  487 conn.commit();
4709    } catch (SQLException e) {
4710  0 if (conn != null) {
4711  0 try {
4712  0 conn.rollback();
4713    } catch (SQLException e1) {
4714  0 log.error("Failed to rollback the API state change record", e1);
4715    }
4716    }
4717  0 handleException("Failed to record API state change", e);
4718    } finally {
4719  487 APIMgtDBUtil.closeAllConnections(selectQuerySt, null, null);
4720  487 APIMgtDBUtil.closeAllConnections(ps, null, resultSet);
4721    }
4722    }
4723   
 
4724  8 toggle public void updateDefaultAPIPublishedVersion(APIIdentifier identifier, String oldStatus, String newStatus)
4725    throws APIManagementException {
4726   
4727  8 Connection conn = null;
4728  8 try {
4729  8 conn = APIMgtDBUtil.getConnection();
4730  8 conn.setAutoCommit(false);
4731   
4732  8 if (!oldStatus.equals(newStatus)) {
4733  8 if ((APIConstants.CREATED.equals(newStatus) || APIConstants.RETIRED.equals(newStatus)) && (
4734    APIConstants.PUBLISHED.equals(oldStatus) || APIConstants.DEPRECATED.equals(oldStatus)
4735    || APIConstants.BLOCKED.equals(oldStatus))) {
4736  1 setPublishedDefVersion(identifier, conn, null);
4737  7 } else if (APIConstants.PUBLISHED.equals(newStatus) || APIConstants.DEPRECATED.equals(newStatus)
4738    || APIConstants.BLOCKED.equals(newStatus)) {
4739  6 setPublishedDefVersion(identifier, conn, identifier.getVersion());
4740    }
4741    }
4742   
4743  8 conn.commit();
4744   
4745    } catch (SQLException e) {
4746  0 handleException("Failed to update published default API state change", e);
4747    } finally {
4748  8 APIMgtDBUtil.closeAllConnections(null, conn, null);
4749    }
4750    }
4751   
 
4752  220 toggle public List<LifeCycleEvent> getLifeCycleEvents(APIIdentifier apiId) throws APIManagementException {
4753  220 Connection connection = null;
4754  220 PreparedStatement prepStmt = null;
4755  220 ResultSet rs = null;
4756  220 String sqlQuery = SQLConstants.GET_LIFECYCLE_EVENT_SQL;
4757   
4758  220 List<LifeCycleEvent> events = new ArrayList<LifeCycleEvent>();
4759  220 try {
4760  220 connection = APIMgtDBUtil.getConnection();
4761  220 prepStmt = connection.prepareStatement(sqlQuery);
4762  220 prepStmt.setString(1, APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
4763  220 prepStmt.setString(2, apiId.getApiName());
4764  220 prepStmt.setString(3, apiId.getVersion());
4765  220 rs = prepStmt.executeQuery();
4766   
4767  682 while (rs.next()) {
4768  462 LifeCycleEvent event = new LifeCycleEvent();
4769  462 event.setApi(apiId);
4770  462 String oldState = rs.getString("PREVIOUS_STATE");
4771    //event.setOldStatus(oldState != null ? APIStatus.valueOf(oldState) : null);
4772  462 event.setOldStatus(oldState != null ? oldState : null);
4773    //event.setNewStatus(APIStatus.valueOf(rs.getString("NEW_STATE")));
4774  462 event.setNewStatus(rs.getString("NEW_STATE"));
4775  462 event.setUserId(rs.getString("USER_ID"));
4776  462 event.setDate(rs.getTimestamp("EVENT_DATE"));
4777  462 events.add(event);
4778    }
4779   
4780  220 Collections.sort(events, new Comparator<LifeCycleEvent>() {
 
4781  242 toggle public int compare(LifeCycleEvent o1, LifeCycleEvent o2) {
4782  242 return o1.getDate().compareTo(o2.getDate());
4783    }
4784    });
4785    } catch (SQLException e) {
4786  0 handleException("Error when executing the SQL : " + sqlQuery, e);
4787    } finally {
4788  220 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
4789    }
4790  220 return events;
4791    }
4792   
 
4793  8 toggle public void makeKeysForwardCompatible(String provider, String apiName, String oldVersion, String newVersion,
4794    String context) throws APIManagementException {
4795   
4796  8 Connection connection = null;
4797  8 PreparedStatement prepStmt = null;
4798  8 PreparedStatement addSubKeySt = null;
4799  8 PreparedStatement getAppSt = null;
4800  8 ResultSet rs = null;
4801   
4802  8 String getSubscriptionDataQuery = SQLConstants.GET_SUBSCRIPTION_DATA_SQL;
4803  8 String addSubKeyMapping = SQLConstants.ADD_SUBSCRIPTION_KEY_MAPPING_SQL;
4804  8 String getApplicationDataQuery = SQLConstants.GET_APPLICATION_DATA_SQL;
4805   
4806  8 try {
4807    // Retrieve all the existing subscription for the old version
4808  8 connection = APIMgtDBUtil.getConnection();
4809   
4810  8 prepStmt = connection.prepareStatement(getSubscriptionDataQuery);
4811  8 prepStmt.setString(1, APIUtil.replaceEmailDomainBack(provider));
4812  8 prepStmt.setString(2, apiName);
4813  8 prepStmt.setString(3, oldVersion);
4814  8 rs = prepStmt.executeQuery();
4815   
4816  8 List<SubscriptionInfo> subscriptionData = new ArrayList<SubscriptionInfo>();
4817  8 Set<Integer> subscribedApplications = new HashSet<Integer>();
4818  8 while (rs.next() && !(APIConstants.SubscriptionStatus.ON_HOLD.equals(rs.getString("SUB_STATUS")))) {
4819  0 SubscriptionInfo info = new SubscriptionInfo();
4820  0 info.subscriptionId = rs.getInt("SUBSCRIPTION_ID");
4821  0 info.tierId = rs.getString("TIER_ID");
4822  0 info.applicationId = rs.getInt("APPLICATION_ID");
4823  0 info.accessToken = rs.getString("ACCESS_TOKEN"); // no decryption needed.
4824  0 info.tokenType = rs.getString("KEY_TYPE");
4825  0 subscriptionData.add(info);
4826    }
4827   
4828  8 Map<Integer, Integer> subscriptionIdMap = new HashMap<Integer, Integer>();
4829  8 APIIdentifier apiId = new APIIdentifier(provider, apiName, newVersion);
4830   
4831  8 for (SubscriptionInfo info : subscriptionData) {
4832  0 try {
4833  0 if (!subscriptionIdMap.containsKey(info.subscriptionId)) {
4834  0 apiId.setTier(info.tierId);
4835  0 int subscriptionId = addSubscription(apiId, context, info.applicationId, APIConstants
4836    .SubscriptionStatus.UNBLOCKED, provider);
4837  0 if (subscriptionId == -1) {
4838  0 String msg = "Unable to add a new subscription for the API: " + apiName +
4839    ":v" + newVersion;
4840  0 log.error(msg);
4841  0 throw new APIManagementException(msg);
4842    }
4843  0 subscriptionIdMap.put(info.subscriptionId, subscriptionId);
4844    }
4845  0 int subscriptionId = subscriptionIdMap.get(info.subscriptionId);
4846  0 connection.setAutoCommit(false);
4847   
4848  0 addSubKeySt = connection.prepareStatement(addSubKeyMapping);
4849  0 addSubKeySt.setInt(1, subscriptionId);
4850  0 addSubKeySt.setString(2, info.accessToken);
4851  0 addSubKeySt.setString(3, info.tokenType);
4852  0 addSubKeySt.execute();
4853  0 connection.commit();
4854   
4855  0 subscribedApplications.add(info.applicationId);
4856    // catching the exception because when copy the api without the option "require re-subscription"
4857    // need to go forward rather throwing the exception
4858    } catch (SubscriptionAlreadyExistingException e) {
4859  0 log.error("Error while adding subscription " + e.getMessage(), e);
4860    }
4861    }
4862   
4863  8 getAppSt = connection.prepareStatement(getApplicationDataQuery);
4864  8 getAppSt.setString(1, APIUtil.replaceEmailDomainBack(provider));
4865  8 getAppSt.setString(2, apiName);
4866  8 getAppSt.setString(3, oldVersion);
4867  8 rs = getAppSt.executeQuery();
4868  12 while (rs.next() && !(APIConstants.SubscriptionStatus.ON_HOLD.equals(rs.getString("SUB_STATUS")))) {
4869  4 int applicationId = rs.getInt("APPLICATION_ID");
4870  4 if (!subscribedApplications.contains(applicationId)) {
4871  4 apiId.setTier(rs.getString("TIER_ID"));
4872  4 try {
4873  4 addSubscription(apiId, rs.getString("CONTEXT"), applicationId, APIConstants
4874    .SubscriptionStatus.UNBLOCKED, provider);
4875    // catching the exception because when copy the api without the option "require re-subscription"
4876    // need to go forward rather throwing the exception
4877    } catch (SubscriptionAlreadyExistingException e) {
4878    //Not handled as an error because same subscription can be there in many previous versions.
4879    //Ex: if previous version was created by another older version and if the subscriptions are
4880    //Forwarded, then the third one will get same subscription from previous two versions.
4881  1 log.info("Subscription already exists: " + e.getMessage());
4882    }
4883    }
4884    }
4885    } catch (SQLException e) {
4886  0 handleException("Error when executing the SQL queries", e);
4887    } finally {
4888  8 APIMgtDBUtil.closeAllConnections(getAppSt, null, null);
4889  8 APIMgtDBUtil.closeAllConnections(addSubKeySt, null, null);
4890  8 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
4891    }
4892    }
4893   
 
4894  270 toggle public void addAPI(API api, int tenantId) throws APIManagementException {
4895  270 Connection connection = null;
4896  270 PreparedStatement prepStmt = null;
4897  270 ResultSet rs = null;
4898   
4899  270 String query = SQLConstants.ADD_API_SQL;
4900  270 try {
4901  270 connection = APIMgtDBUtil.getConnection();
4902  270 connection.setAutoCommit(false);
4903   
4904  270 prepStmt = connection.prepareStatement(query, new String[]{"api_id"});
4905  270 prepStmt.setString(1, APIUtil.replaceEmailDomainBack(api.getId().getProviderName()));
4906  270 prepStmt.setString(2, api.getId().getApiName());
4907  270 prepStmt.setString(3, api.getId().getVersion());
4908  270 prepStmt.setString(4, api.getContext());
4909  270 String contextTemplate = api.getContextTemplate();
4910    //Validate if the API has an unsupported context before executing the query
4911  270 String invalidContext = "/" + APIConstants.VERSION_PLACEHOLDER;
4912  270 if (invalidContext.equals(contextTemplate)) {
4913  0 throw new APIManagementException("Cannot add API : " + api.getId() + " with unsupported context : "
4914    + contextTemplate);
4915    }
4916    //If the context template ends with {version} this means that the version will be at the end of the context.
4917  270 if (contextTemplate.endsWith("/" + APIConstants.VERSION_PLACEHOLDER)) {
4918    //Remove the {version} part from the context template.
4919  266 contextTemplate = contextTemplate.split(Pattern.quote("/" + APIConstants.VERSION_PLACEHOLDER))[0];
4920    }
4921  270 prepStmt.setString(5, contextTemplate);
4922  270 prepStmt.setString(6, APIUtil.replaceEmailDomainBack(api.getId().getProviderName()));
4923  270 prepStmt.setTimestamp(7, new Timestamp(System.currentTimeMillis()));
4924  270 prepStmt.setString(8, api.getApiLevelPolicy());
4925  270 prepStmt.execute();
4926   
4927  270 rs = prepStmt.getGeneratedKeys();
4928  270 int apiId = -1;
4929  270 if (rs.next()) {
4930  270 apiId = rs.getInt(1);
4931    }
4932   
4933  270 connection.commit();
4934   
4935  270 if (api.getScopes() != null) {
4936  45 addScopes(api.getScopes(), api.getId(), apiId, tenantId);
4937    }
4938  270 addURLTemplates(apiId, api, connection);
4939  270 String tenantUserName = MultitenantUtils
4940    .getTenantAwareUsername(APIUtil.replaceEmailDomainBack(api.getId().getProviderName()));
4941  270 recordAPILifeCycleEvent(api.getId(), null, APIStatus.CREATED.toString(), tenantUserName, tenantId,
4942    connection);
4943    //If the api is selected as default version, it is added/replaced into AM_API_DEFAULT_VERSION table
4944  270 if (api.isDefaultVersion()) {
4945  24 addUpdateAPIAsDefaultVersion(api, connection);
4946    }
4947  270 connection.commit();
4948    } catch (SQLException e) {
4949  0 handleException("Error while adding the API: " + api.getId() + " to the database", e);
4950    } finally {
4951  270 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
4952    }
4953    }
4954   
 
4955  494 toggle public String getDefaultVersion(APIIdentifier apiId) throws APIManagementException {
4956  494 Connection connection = null;
4957  494 PreparedStatement prepStmt = null;
4958  494 ResultSet rs = null;
4959  494 String oldDefaultVersion = null;
4960   
4961  494 String query = SQLConstants.GET_DEFAULT_VERSION_SQL;
4962  494 try {
4963   
4964  494 connection = APIMgtDBUtil.getConnection();
4965  494 prepStmt = connection.prepareStatement(query);
4966  494 prepStmt.setString(1, apiId.getApiName());
4967  494 prepStmt.setString(2, APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
4968   
4969  494 rs = prepStmt.executeQuery();
4970   
4971  494 if (rs.next()) {
4972  54 oldDefaultVersion = rs.getString("DEFAULT_API_VERSION");
4973    }
4974    } catch (SQLException e) {
4975  0 handleException("Error while getting default version for " + apiId.getApiName(), e);
4976    } finally {
4977  494 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
4978    }
4979  494 return oldDefaultVersion;
4980    }
4981   
4982    /**
4983    * Persists WorkflowDTO to Database
4984    *
4985    * @param workflow
4986    * @throws APIManagementException
4987    */
 
4988  3 toggle public void addWorkflowEntry(WorkflowDTO workflow) throws APIManagementException {
4989  3 Connection connection = null;
4990  3 PreparedStatement prepStmt = null;
4991   
4992  3 String query = SQLConstants.ADD_WORKFLOW_ENTRY_SQL;
4993  3 try {
4994  3 Timestamp cratedDateStamp = new Timestamp(workflow.getCreatedTime());
4995   
4996  3 connection = APIMgtDBUtil.getConnection();
4997  3 connection.setAutoCommit(false);
4998   
4999  3 prepStmt = connection.prepareStatement(query);
5000  3 prepStmt.setString(1, workflow.getWorkflowReference());
5001  3 prepStmt.setString(2, workflow.getWorkflowType());
5002  3 prepStmt.setString(3, workflow.getStatus().toString());
5003  3 prepStmt.setTimestamp(4, cratedDateStamp);
5004  3 prepStmt.setString(5, workflow.getWorkflowDescription());
5005  3 prepStmt.setInt(6, workflow.getTenantId());
5006  3 prepStmt.setString(7, workflow.getTenantDomain());
5007  3 prepStmt.setString(8, workflow.getExternalWorkflowReference());
5008   
5009  3 prepStmt.execute();
5010   
5011  3 connection.commit();
5012    } catch (SQLException e) {
5013  0 handleException("Error while adding Workflow : " + workflow.getExternalWorkflowReference() + " to the " +
5014    "database", e);
5015    } finally {
5016  3 APIMgtDBUtil.closeAllConnections(prepStmt, connection, null);
5017    }
5018    }
5019   
 
5020  2 toggle public void updateWorkflowStatus(WorkflowDTO workflowDTO) throws APIManagementException {
5021  2 Connection connection = null;
5022  2 PreparedStatement prepStmt = null;
5023   
5024  2 String query = SQLConstants.UPDATE_WORKFLOW_ENTRY_SQL;
5025  2 try {
5026  2 Timestamp updatedTimeStamp = new Timestamp(workflowDTO.getUpdatedTime());
5027   
5028  2 connection = APIMgtDBUtil.getConnection();
5029  2 connection.setAutoCommit(false);
5030   
5031  2 prepStmt = connection.prepareStatement(query);
5032  2 prepStmt.setString(1, workflowDTO.getStatus().toString());
5033  2 prepStmt.setString(2, workflowDTO.getWorkflowDescription());
5034  2 prepStmt.setString(3, workflowDTO.getExternalWorkflowReference());
5035   
5036  2 prepStmt.execute();
5037   
5038  2 connection.commit();
5039    } catch (SQLException e) {
5040  0 handleException("Error while updating Workflow Status of workflow " + workflowDTO
5041    .getExternalWorkflowReference(), e);
5042    } finally {
5043  2 APIMgtDBUtil.closeAllConnections(prepStmt, connection, null);
5044    }
5045    }
5046   
5047    /**
5048    * Returns a workflow object for a given external workflow reference.
5049    *
5050    * @param workflowReference
5051    * @return
5052    * @throws APIManagementException
5053    */
 
5054  4 toggle public WorkflowDTO retrieveWorkflow(String workflowReference) throws APIManagementException {
5055  4 Connection connection = null;
5056  4 PreparedStatement prepStmt = null;
5057  4 ResultSet rs = null;
5058  4 WorkflowDTO workflowDTO = null;
5059   
5060  4 String query = SQLConstants.GET_ALL_WORKFLOW_ENTRY_SQL;
5061  4 try {
5062  4 connection = APIMgtDBUtil.getConnection();
5063  4 prepStmt = connection.prepareStatement(query);
5064  4 prepStmt.setString(1, workflowReference);
5065   
5066  4 rs = prepStmt.executeQuery();
5067  7 while (rs.next()) {
5068  3 workflowDTO = WorkflowExecutorFactory.getInstance().createWorkflowDTO(rs.getString("WF_TYPE"));
5069  3 workflowDTO.setStatus(WorkflowStatus.valueOf(rs.getString("WF_STATUS")));
5070  3 workflowDTO.setExternalWorkflowReference(rs.getString("WF_EXTERNAL_REFERENCE"));
5071  3 workflowDTO.setCreatedTime(rs.getTimestamp("WF_CREATED_TIME").getTime());
5072  3 workflowDTO.setWorkflowReference(rs.getString("WF_REFERENCE"));
5073  3 workflowDTO.setTenantDomain(rs.getString("TENANT_DOMAIN"));
5074  3 workflowDTO.setTenantId(rs.getInt("TENANT_ID"));
5075  3 workflowDTO.setWorkflowDescription(rs.getString("WF_STATUS_DESC"));
5076    }
5077    } catch (SQLException e) {
5078  0 handleException("Error while retrieving workflow details for " + workflowReference, e);
5079    } finally {
5080  4 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
5081    }
5082  4 return workflowDTO;
5083    }
5084   
5085    /**
5086    * Returns a workflow object for a given internal workflow reference and the workflow type.
5087    *
5088    * @param workflowReference
5089    * @param workflowType
5090    * @return
5091    * @throws APIManagementException
5092    */
 
5093  921 toggle public WorkflowDTO retrieveWorkflowFromInternalReference(String workflowReference, String workflowType)
5094    throws APIManagementException {
5095  921 Connection connection = null;
5096  921 PreparedStatement prepStmt = null;
5097  921 ResultSet rs = null;
5098  921 WorkflowDTO workflowDTO = null;
5099   
5100  921 String query = SQLConstants.GET_ALL_WORKFLOW_ENTRY_FROM_INTERNAL_REF_SQL;
5101  921 try {
5102  921 connection = APIMgtDBUtil.getConnection();
5103  921 prepStmt = connection.prepareStatement(query);
5104  921 prepStmt.setString(1, workflowReference);
5105  921 prepStmt.setString(2, workflowType);
5106   
5107  921 rs = prepStmt.executeQuery();
5108  930 while (rs.next()) {
5109  9 workflowDTO = WorkflowExecutorFactory.getInstance().createWorkflowDTO(rs.getString("WF_TYPE"));
5110  9 workflowDTO.setStatus(WorkflowStatus.valueOf(rs.getString("WF_STATUS")));
5111  9 workflowDTO.setExternalWorkflowReference(rs.getString("WF_EXTERNAL_REFERENCE"));
5112  9 workflowDTO.setCreatedTime(rs.getTimestamp("WF_CREATED_TIME").getTime());
5113  9 workflowDTO.setWorkflowReference(rs.getString("WF_REFERENCE"));
5114  9 workflowDTO.setTenantDomain(rs.getString("TENANT_DOMAIN"));
5115  9 workflowDTO.setTenantId(rs.getInt("TENANT_ID"));
5116  9 workflowDTO.setWorkflowDescription(rs.getString("WF_STATUS_DESC"));
5117    }
5118    } catch (SQLException e) {
5119  0 handleException("Error while retrieving workflow details for " + workflowReference, e);
5120    } finally {
5121  921 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
5122    }
5123  921 return workflowDTO;
5124    }
5125   
 
5126  7 toggle private void setPublishedDefVersion(APIIdentifier apiId, Connection connection, String value)
5127    throws APIManagementException {
5128  7 String queryDefaultVersionUpdate = SQLConstants.UPDATE_PUBLISHED_DEFAULT_VERSION_SQL;
5129   
5130  7 PreparedStatement prepStmtDefVersionUpdate = null;
5131  7 try {
5132  7 prepStmtDefVersionUpdate = connection.prepareStatement(queryDefaultVersionUpdate);
5133  7 prepStmtDefVersionUpdate.setString(1, value);
5134  7 prepStmtDefVersionUpdate.setString(2, apiId.getApiName());
5135  7 prepStmtDefVersionUpdate.setString(3, APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
5136  7 prepStmtDefVersionUpdate.execute();
5137    } catch (SQLException e) {
5138  0 handleException("Error while deleting the API default version entry: " + apiId.getApiName() + " from the " +
5139    "database", e);
5140    } finally {
5141  7 APIMgtDBUtil.closeAllConnections(prepStmtDefVersionUpdate, null, null);
5142    }
5143    }
5144   
5145    /**
5146    * Sets/removes default api entry such that api will not represent as default api further.
5147    * If the api's version is the same as the published version, then the whole entry will be removed.
5148    * Otherwise only the default version attribute is set to null.
5149    *
5150    * @param apiId
5151    * @param connection
5152    * @return
5153    * @throws APIManagementException
5154    */
 
5155  45 toggle public void removeAPIFromDefaultVersion(APIIdentifier apiId, Connection connection) throws APIManagementException {
5156   
5157  45 String queryDefaultVersionDelete = SQLConstants.REMOVE_API_DEFAULT_VERSION_SQL;
5158   
5159  45 PreparedStatement prepStmtDefVersionDelete = null;
5160  45 try {
5161  45 prepStmtDefVersionDelete = connection.prepareStatement(queryDefaultVersionDelete);
5162  45 prepStmtDefVersionDelete.setString(1, apiId.getApiName());
5163  45 prepStmtDefVersionDelete.setString(2, APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
5164  45 prepStmtDefVersionDelete.execute();
5165    } catch (SQLException e) {
5166  0 handleException("Error while deleting the API default version entry: " + apiId.getApiName() + " from the " +
5167    "database", e);
5168    } finally {
5169  45 APIMgtDBUtil.closeAllConnections(prepStmtDefVersionDelete, null, null);
5170    }
5171    }
5172   
 
5173  1042 toggle public String getPublishedDefaultVersion(APIIdentifier apiId) throws APIManagementException {
5174  1042 Connection connection = null;
5175  1042 PreparedStatement prepStmt = null;
5176  1042 ResultSet rs = null;
5177  1042 String publishedDefaultVersion = null;
5178   
5179  1042 String query = SQLConstants.GET_PUBLISHED_DEFAULT_VERSION_SQL;
5180  1042 try {
5181  1042 connection = APIMgtDBUtil.getConnection();
5182  1042 prepStmt = connection.prepareStatement(query);
5183  1042 prepStmt.setString(1, apiId.getApiName());
5184  1042 prepStmt.setString(2, APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
5185   
5186  1042 rs = prepStmt.executeQuery();
5187   
5188  1117 while (rs.next()) {
5189  75 publishedDefaultVersion = rs.getString("PUBLISHED_DEFAULT_API_VERSION");
5190    }
5191    } catch (SQLException e) {
5192  0 handleException("Error while getting default version for " + apiId.getApiName(), e);
5193    } finally {
5194  1042 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
5195    }
5196  1042 return publishedDefaultVersion;
5197    }
5198   
 
5199  24 toggle public void addUpdateAPIAsDefaultVersion(API api, Connection connection) throws APIManagementException {
5200  24 String publishedDefaultVersion = getPublishedDefaultVersion(api.getId());
5201  24 removeAPIFromDefaultVersion(api.getId(), connection);
5202   
5203  24 PreparedStatement prepStmtDefVersionAdd = null;
5204  24 String queryDefaultVersionAdd = SQLConstants.ADD_API_DEFAULT_VERSION_SQL;
5205  24 try {
5206  24 prepStmtDefVersionAdd = connection.prepareStatement(queryDefaultVersionAdd);
5207  24 prepStmtDefVersionAdd.setString(1, api.getId().getApiName());
5208  24 prepStmtDefVersionAdd.setString(2, APIUtil.replaceEmailDomainBack(api.getId().getProviderName()));
5209  24 prepStmtDefVersionAdd.setString(3, api.getId().getVersion());
5210  24 String apistatus = api.getStatus();
5211  24 if (APIConstants.PUBLISHED.equals(apistatus) || APIConstants.DEPRECATED.equals(apistatus) || APIConstants
5212    .BLOCKED.equals(apistatus)) {
5213  0 prepStmtDefVersionAdd.setString(4, api.getId().getVersion());
5214    } else {
5215  24 prepStmtDefVersionAdd.setString(4, publishedDefaultVersion);
5216    }
5217   
5218  24 prepStmtDefVersionAdd.execute();
5219    } catch (SQLException e) {
5220  0 handleException("Error while adding the API default version entry: " + api.getId().getApiName() + " to " +
5221    "the database", e);
5222    } finally {
5223  24 APIMgtDBUtil.closeAllConnections(prepStmtDefVersionAdd, null, null);
5224    }
5225    }
5226   
5227    /**
5228    * Adds URI templates define for an API
5229    *
5230    * @param apiId
5231    * @param api
5232    * @param connection
5233    * @throws APIManagementException
5234    */
 
5235  336 toggle public void addURLTemplates(int apiId, API api, Connection connection) throws APIManagementException {
5236  336 if (apiId == -1) {
5237    //application addition has failed
5238  0 return;
5239    }
5240  336 PreparedStatement prepStmt = null;
5241  336 PreparedStatement scopePrepStmt = null;
5242   
5243  336 String query = SQLConstants.ADD_URL_MAPPING_SQL;
5244  336 String scopeQuery = SQLConstants.ADD_OAUTH2_RESOURCE_SCOPE_SQL;
5245  336 try {
5246  336 prepStmt = connection.prepareStatement(query);
5247  336 scopePrepStmt = connection.prepareStatement(scopeQuery);
5248   
5249  336 Iterator<URITemplate> uriTemplateIterator = api.getUriTemplates().iterator();
5250  336 URITemplate uriTemplate;
5251  898 for (; uriTemplateIterator.hasNext(); ) {
5252  562 uriTemplate = uriTemplateIterator.next();
5253   
5254  562 prepStmt.setInt(1, apiId);
5255  562 prepStmt.setString(2, uriTemplate.getHTTPVerb());
5256  562 prepStmt.setString(3, uriTemplate.getAuthType());
5257  562 prepStmt.setString(4, uriTemplate.getUriTemplate());
5258    //If API policy is available then set it for all the resources
5259  562 if (StringUtils.isEmpty(api.getApiLevelPolicy())) {
5260  560 prepStmt.setString(5, uriTemplate.getThrottlingTier());
5261    } else {
5262  2 prepStmt.setString(5, api.getApiLevelPolicy());
5263    }
5264  562 InputStream is;
5265  562 if (uriTemplate.getMediationScript() != null) {
5266  24 is = new ByteArrayInputStream(uriTemplate.getMediationScript().getBytes(Charset.defaultCharset()));
5267    } else {
5268  538 is = null;
5269    }
5270  562 if (connection.getMetaData().getDriverName().contains("PostgreSQL") || connection.getMetaData()
5271    .getDatabaseProductName().contains("DB2")) {
5272  0 if (uriTemplate.getMediationScript() != null) {
5273  0 prepStmt.setBinaryStream(6, is, uriTemplate.getMediationScript().getBytes(Charset.defaultCharset()).length);
5274    } else {
5275  0 prepStmt.setBinaryStream(6, is, 0);
5276    }
5277    } else {
5278  562 prepStmt.setBinaryStream(6, is);
5279    }
5280  562 prepStmt.addBatch();
5281  562 if (uriTemplate.getScope() != null) {
5282  26 scopePrepStmt.setString(1, APIUtil.getResourceKey(api, uriTemplate));
5283   
5284  26 if (uriTemplate.getScope().getId() == 0) {
5285  6 String scopeKey = uriTemplate.getScope().getKey();
5286  6 Scope scopeByKey = APIUtil.findScopeByKey(api.getScopes(), scopeKey);
5287  6 if (scopeByKey != null) {
5288  6 if (scopeByKey.getId() > 0) {
5289  6 uriTemplate.getScopes().setId(scopeByKey.getId());
5290    }
5291    }
5292    }
5293   
5294  26 scopePrepStmt.setInt(2, uriTemplate.getScope().getId());
5295  26 scopePrepStmt.setInt(3, APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(api.getId()
5296    .getProviderName())));
5297  26 scopePrepStmt.addBatch();
5298    }
5299    }
5300  336 prepStmt.executeBatch();
5301  336 prepStmt.clearBatch();
5302  336 scopePrepStmt.executeBatch();
5303  336 scopePrepStmt.clearBatch();
5304    } catch (SQLException e) {
5305  0 handleException("Error while adding URL template(s) to the database for API : " + api.getId(), e);
5306    } finally {
5307  336 APIMgtDBUtil.closeAllConnections(prepStmt, null, null);
5308  336 APIMgtDBUtil.closeAllConnections(scopePrepStmt, null, null);
5309    }
5310    }
5311   
5312    /**
5313    * Fetches an Application with OAuth Apps, by name.
5314    *
5315    * @param applicationName Name of the Application
5316    * @param userId Name of the User.
5317    * @param groupId Group ID
5318    * @throws APIManagementException
5319    */
 
5320  156 toggle public Application getApplicationWithOAuthApps(String applicationName, String userId, String groupId)
5321    throws APIManagementException {
5322   
5323  156 Application application = getApplicationByName(applicationName, userId, groupId);
5324   
5325  156 if (application != null) {
5326  142 Map<String, OAuthApplicationInfo> keyMap = getOAuthApplications(application.getId());
5327   
5328  142 for (Map.Entry<String, OAuthApplicationInfo> entry : keyMap.entrySet()) {
5329  110 application.addOAuthApp(entry.getKey(), entry.getValue());
5330    }
5331    }
5332   
5333  156 return application;
5334    }
5335   
5336    /**
5337    * Checks whether application is accessible to the specified user
5338    *
5339    * @param applicationID ID of the Application
5340    * @param userId Name of the User.
5341    * @param groupId Group IDs
5342    * @throws APIManagementException
5343    */
 
5344  168 toggle public boolean isAppAllowed(int applicationID, String userId, String groupId)
5345    throws APIManagementException {
5346  168 Connection connection = null;
5347  168 PreparedStatement prepStmt = null;
5348  168 ResultSet rs = null;
5349   
5350  168 try {
5351  168 connection = APIMgtDBUtil.getConnection();
5352   
5353  168 String query = "SELECT APP.APPLICATION_ID FROM AM_SUBSCRIBER SUB, AM_APPLICATION APP";
5354  168 String whereClause = " WHERE SUB.USER_ID =? AND APP.APPLICATION_ID=? AND " +
5355    "SUB.SUBSCRIBER_ID=APP.SUBSCRIBER_ID";
5356  168 String whereClauseCaseInSensitive = " WHERE LOWER(SUB.USER_ID) =LOWER(?) AND APP.APPLICATION_ID=? AND SUB"
5357    + ".SUBSCRIBER_ID=APP.SUBSCRIBER_ID";
5358  168 String whereClauseWithGroupId = " WHERE (APP.GROUP_ID = ? OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL)"
5359    + " AND SUB.USER_ID = ?)) AND " + "APP.APPLICATION_ID = ? AND SUB.SUBSCRIBER_ID = APP.SUBSCRIBER_ID";
5360   
5361  168 String whereClauseWithMultiGroupId = " WHERE ((APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM " +
5362    "AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?)) OR SUB.USER_ID = ? " +
5363    "OR (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM AM_APPLICATION WHERE GROUP_ID = ?))) " +
5364    "AND APP.APPLICATION_ID = ? AND SUB.SUBSCRIBER_ID = APP.SUBSCRIBER_ID";
5365   
5366  168 if (!StringUtils.isEmpty(groupId) && !APIConstants.NULL_GROUPID_LIST.equals(groupId)) {
5367  0 if (multiGroupAppSharingEnabled) {
5368  0 Subscriber subscriber = getSubscriber(userId);
5369  0 String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
5370  0 query += whereClauseWithMultiGroupId;
5371  0 String[] groupIds = groupId.split(",");
5372  0 int parameterIndex = groupIds.length;
5373   
5374  0 prepStmt = fillQueryParams(connection, query, groupIds, 1);
5375  0 prepStmt.setString(++parameterIndex, tenantDomain);
5376  0 prepStmt.setString(++parameterIndex, userId);
5377  0 prepStmt.setString(++parameterIndex, tenantDomain + '/' + groupId);
5378  0 prepStmt.setInt(++parameterIndex, applicationID);
5379    } else {
5380  0 query += whereClauseWithGroupId;
5381  0 prepStmt = connection.prepareStatement(query);
5382  0 prepStmt.setString(1, groupId);
5383  0 prepStmt.setString(2, userId);
5384  0 prepStmt.setInt(3, applicationID);
5385    }
5386    } else {
5387  168 if (forceCaseInsensitiveComparisons) {
5388  168 query += whereClauseCaseInSensitive;
5389    } else {
5390  0 query += whereClause;
5391    }
5392  168 prepStmt = connection.prepareStatement(query);
5393  168 prepStmt.setString(1, userId);
5394  168 prepStmt.setInt(2, applicationID);
5395    }
5396   
5397  168 rs = prepStmt.executeQuery();
5398  168 while (rs.next()) {
5399  167 return true;
5400    }
5401    } catch (SQLException e) {
5402  0 handleException("Error while checking whether the application : " + applicationID + " is accessible " +
5403    "to user " + userId, e);
5404    } finally {
5405  168 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
5406    }
5407  1 return false;
5408    }
5409   
5410    /**
5411    * Fetches an Application by name.
5412    *
5413    * @param applicationName Name of the Application
5414    * @param userId Name of the User.
5415    * @param groupId Group ID
5416    * @throws APIManagementException
5417    */
 
5418  424 toggle public Application getApplicationByName(String applicationName, String userId, String groupId)
5419    throws APIManagementException {
5420    //mysql> select APP.APPLICATION_ID, APP.NAME, APP.SUBSCRIBER_ID,APP.APPLICATION_TIER,APP.CALLBACK_URL,APP
5421    // .DESCRIPTION,
5422    // APP.APPLICATION_STATUS from AM_SUBSCRIBER as SUB,AM_APPLICATION as APP
5423    // where SUB.user_id='admin' AND APP.name='DefaultApplication' AND SUB.SUBSCRIBER_ID=APP.SUBSCRIBER_ID;
5424  424 Connection connection = null;
5425  424 PreparedStatement prepStmt = null;
5426  424 ResultSet rs = null;
5427   
5428  424 int applicationId = 0;
5429  424 Application application = null;
5430  424 try {
5431  424 connection = APIMgtDBUtil.getConnection();
5432   
5433  424 String query = SQLConstants.GET_APPLICATION_BY_NAME_PREFIX;
5434  424 String whereClause = " WHERE SUB.USER_ID =? AND APP.NAME=? AND SUB.SUBSCRIBER_ID=APP.SUBSCRIBER_ID";
5435  424 String whereClauseCaseInSensitive = " WHERE LOWER(SUB.USER_ID) =LOWER(?) AND APP.NAME=? AND SUB" + "" +
5436    ".SUBSCRIBER_ID=APP.SUBSCRIBER_ID";
5437  424 String whereClauseWithGroupId = " WHERE (APP.GROUP_ID = ? OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL)"
5438    + " AND SUB.USER_ID = ?)) AND " + "APP.NAME = ? AND SUB.SUBSCRIBER_ID = APP.SUBSCRIBER_ID";
5439   
5440  424 String whereClauseWithMultiGroupId = " WHERE ((APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM " +
5441    "AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?)) OR SUB.USER_ID = ? " +
5442    "OR (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM AM_APPLICATION WHERE GROUP_ID = ?))) " +
5443    "AND APP.NAME = ? AND SUB.SUBSCRIBER_ID = APP.SUBSCRIBER_ID";
5444   
5445  424 if (groupId != null && !"null".equals(groupId) && !groupId.isEmpty()) {
5446  0 if (multiGroupAppSharingEnabled) {
5447  0 Subscriber subscriber = getSubscriber(userId);
5448  0 String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
5449  0 query += whereClauseWithMultiGroupId;
5450  0 String[] groupIds = groupId.split(",");
5451  0 int parameterIndex = groupIds.length;
5452    //
5453  0 prepStmt = fillQueryParams(connection, query, groupIds, 1);
5454  0 prepStmt.setString(++parameterIndex, tenantDomain);
5455  0 prepStmt.setString(++parameterIndex, userId);
5456  0 prepStmt.setString(++parameterIndex, tenantDomain + '/' + groupId);
5457  0 prepStmt.setString(++parameterIndex, applicationName);
5458    } else {
5459  0 query += whereClauseWithGroupId;
5460  0 prepStmt = connection.prepareStatement(query);
5461  0 prepStmt.setString(1, groupId);
5462  0 prepStmt.setString(2, userId);
5463  0 prepStmt.setString(3, applicationName);
5464    }
5465    } else {
5466  424 if (forceCaseInsensitiveComparisons) {
5467  424 query = query + whereClauseCaseInSensitive;
5468    } else {
5469  0 query = query + whereClause;
5470    }
5471  424 prepStmt = connection.prepareStatement(query);
5472  424 prepStmt.setString(1, userId);
5473  424 prepStmt.setString(2, applicationName);
5474    }
5475   
5476  424 rs = prepStmt.executeQuery();
5477  820 while (rs.next()) {
5478  396 String subscriberId = rs.getString("SUBSCRIBER_ID");
5479  396 String subscriberName = rs.getString("USER_ID");
5480   
5481  396 Subscriber subscriber = new Subscriber(subscriberName);
5482  396 subscriber.setId(Integer.parseInt(subscriberId));
5483  396 application = new Application(applicationName, subscriber);
5484   
5485  396 application.setDescription(rs.getString("DESCRIPTION"));
5486  396 application.setStatus(rs.getString("APPLICATION_STATUS"));
5487  396 application.setCallbackUrl(rs.getString("CALLBACK_URL"));
5488  396 applicationId = rs.getInt("APPLICATION_ID");
5489  396 application.setId(applicationId);
5490  396 application.setTier(rs.getString("APPLICATION_TIER"));
5491  396 application.setUUID(rs.getString("UUID"));
5492  396 application.setGroupId(rs.getString("GROUP_ID"));
5493  396 application.setOwner(rs.getString("CREATED_BY"));
5494  396 application.setTokenType(rs.getString("TOKEN_TYPE"));
5495   
5496  396 if (multiGroupAppSharingEnabled) {
5497  0 setGroupIdInApplication(application);
5498    }
5499  396 if (application != null) {
5500  396 Map<String, String> applicationAttributes = getApplicationAttributes(connection, applicationId);
5501  396 application.setApplicationAttributes(applicationAttributes);
5502    }
5503    }
5504    } catch (SQLException e) {
5505  0 handleException("Error while obtaining details of the Application : " + applicationName, e);
5506    } finally {
5507  424 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
5508    }
5509  424 return application;
5510    }
5511   
 
5512  0 toggle private void setGroupIdInApplication(Application application) throws APIManagementException {
5513  0 String applicationGroupId = application.getGroupId();
5514  0 if (StringUtils.isEmpty(applicationGroupId)) { // No migrated App groupId
5515  0 application.setGroupId(getGroupId(application.getId()));
5516    } else {
5517    // Migrated data exists where Group ID for this App has been stored in AM_APPLICATION table
5518    // in the format 'tenant/groupId', so extract groupId value and store it in the App object
5519  0 String[] split = applicationGroupId.split("/");
5520  0 if (split.length == 2) {
5521  0 application.setGroupId(split[1]);
5522    } else {
5523  0 log.error("Migrated Group ID: " + applicationGroupId +
5524    "does not follow the expected format 'tenant/groupId'");
5525    }
5526    }
5527    }
5528   
 
5529  184 toggle public Application getApplicationById(int applicationId) throws APIManagementException {
5530  184 Connection connection = null;
5531  184 PreparedStatement prepStmt = null;
5532  184 ResultSet rs = null;
5533   
5534  184 Application application = null;
5535  184 try {
5536  184 connection = APIMgtDBUtil.getConnection();
5537   
5538  184 String query = SQLConstants.GET_APPLICATION_BY_ID_SQL;
5539  184 prepStmt = connection.prepareStatement(query);
5540  184 prepStmt.setInt(1, applicationId);
5541   
5542  184 rs = prepStmt.executeQuery();
5543  184 if (rs.next()) {
5544  184 String applicationName = rs.getString("NAME");
5545  184 String subscriberId = rs.getString("SUBSCRIBER_ID");
5546  184 String subscriberName = rs.getString("USER_ID");
5547   
5548  184 Subscriber subscriber = new Subscriber(subscriberName);
5549  184 subscriber.setId(Integer.parseInt(subscriberId));
5550  184 application = new Application(applicationName, subscriber);
5551   
5552  184 application.setDescription(rs.getString("DESCRIPTION"));
5553  184 application.setStatus(rs.getString("APPLICATION_STATUS"));
5554  184 application.setCallbackUrl(rs.getString("CALLBACK_URL"));
5555  184 application.setId(rs.getInt("APPLICATION_ID"));
5556  184 application.setGroupId(rs.getString("GROUP_ID"));
5557  184 application.setUUID(rs.getString("UUID"));
5558  184 application.setTier(rs.getString("APPLICATION_TIER"));
5559  184 application.setTokenType(rs.getString("TOKEN_TYPE"));
5560  184 subscriber.setId(rs.getInt("SUBSCRIBER_ID"));
5561    }
5562  184 if (application != null) {
5563  184 Map<String,String> applicationAttributes = getApplicationAttributes(connection, applicationId);
5564  184 application.setApplicationAttributes(applicationAttributes);
5565    }
5566    } catch (SQLException e) {
5567  0 handleException("Error while obtaining details of the Application : " + applicationId, e);
5568    } finally {
5569  184 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
5570    }
5571  184 return application;
5572    }
5573   
5574    /**
5575    * Retrieves the Application which is corresponding to the given UUID String
5576    *
5577    * @param uuid UUID of Application
5578    * @return
5579    * @throws APIManagementException
5580    */
 
5581  53 toggle public Application getApplicationByUUID(String uuid) throws APIManagementException {
5582  53 Connection connection = null;
5583  53 PreparedStatement prepStmt = null;
5584  53 ResultSet rs = null;
5585  53 int applicationId = 0;
5586   
5587  53 Application application = null;
5588  53 try {
5589  53 connection = APIMgtDBUtil.getConnection();
5590  53 String query = SQLConstants.GET_APPLICATION_BY_UUID_SQL;
5591   
5592  53 prepStmt = connection.prepareStatement(query);
5593  53 prepStmt.setString(1, uuid);
5594   
5595  53 rs = prepStmt.executeQuery();
5596  53 if (rs.next()) {
5597  52 String applicationName = rs.getString("NAME");
5598  52 String subscriberId = rs.getString("SUBSCRIBER_ID");
5599  52 String subscriberName = rs.getString("USER_ID");
5600   
5601  52 Subscriber subscriber = new Subscriber(subscriberName);
5602  52 subscriber.setId(Integer.parseInt(subscriberId));
5603  52 application = new Application(applicationName, subscriber);
5604   
5605  52 application.setDescription(rs.getString("DESCRIPTION"));
5606  52 application.setStatus(rs.getString("APPLICATION_STATUS"));
5607  52 application.setCallbackUrl(rs.getString("CALLBACK_URL"));
5608  52 applicationId = rs.getInt("APPLICATION_ID");
5609  52 application.setId(applicationId);
5610  52 application.setGroupId(rs.getString("GROUP_ID"));
5611  52 application.setUUID(rs.getString("UUID"));
5612  52 application.setTier(rs.getString("APPLICATION_TIER"));
5613  52 application.setTokenType(rs.getString("TOKEN_TYPE"));
5614  52 subscriber.setId(rs.getInt("SUBSCRIBER_ID"));
5615   
5616  52 if (multiGroupAppSharingEnabled) {
5617  0 if (application.getGroupId().isEmpty()) {
5618  0 application.setGroupId(getGroupId(application.getId()));
5619    }
5620    }
5621   
5622  52 Timestamp createdTime = rs.getTimestamp("CREATED_TIME");
5623  52 application.setCreatedTime(createdTime == null ? null : String.valueOf(createdTime.getTime()));
5624  52 try {
5625  52 Timestamp updated_time = rs.getTimestamp("UPDATED_TIME");
5626  52 application.setLastUpdatedTime(
5627  52 updated_time == null ? null : String.valueOf(updated_time.getTime()));
5628    } catch (SQLException e) {
5629    // fixing Timestamp issue with default value '0000-00-00 00:00:00'for existing applications created
5630  0 application.setLastUpdatedTime(application.getCreatedTime());
5631    }
5632    }
5633    // Get custom attributes of application
5634  53 if (application != null) {
5635  52 Map<String, String> applicationAttributes = getApplicationAttributes(connection, applicationId);
5636  52 application.setApplicationAttributes(applicationAttributes);
5637    }
5638    } catch (SQLException e) {
5639  0 handleException("Error while obtaining details of the Application : " + uuid, e);
5640    } finally {
5641  53 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
5642    }
5643  53 return application;
5644    }
5645   
5646    /**
5647    * update URI templates define for an API
5648    *
5649    * @param api
5650    * @throws APIManagementException
5651    */
 
5652  66 toggle public void updateURLTemplates(API api) throws APIManagementException {
5653   
5654  66 Connection connection = null;
5655  66 PreparedStatement prepStmt = null;
5656  66 int apiId;
5657   
5658  66 String deleteOldMappingsQuery = SQLConstants.REMOVE_FROM_URI_TEMPLATES_SQL;
5659  66 try {
5660  66 connection = APIMgtDBUtil.getConnection();
5661  66 connection.setAutoCommit(false);
5662   
5663  66 apiId = getAPIID(api.getId(), connection);
5664  66 if (apiId == -1) {
5665    //application addition has failed
5666  0 return;
5667    }
5668  66 prepStmt = connection.prepareStatement(deleteOldMappingsQuery);
5669  66 prepStmt.setInt(1, apiId);
5670  66 prepStmt.execute();
5671   
5672  66 addURLTemplates(apiId, api, connection);
5673   
5674  66 connection.commit();
5675    } catch (SQLException e) {
5676  0 handleException("Error while deleting URL template(s) for API : " + api.getId(), e);
5677    } finally {
5678  66 APIMgtDBUtil.closeAllConnections(prepStmt, connection, null);
5679    }
5680    }
5681   
5682    /**
5683    * returns all URL templates define for all active(PUBLISHED) APIs.
5684    */
 
5685  725 toggle public ArrayList<URITemplate> getAllURITemplates(String apiContext, String version) throws APIManagementException {
5686  725 if (APIUtil.isAdvanceThrottlingEnabled()) {
5687  712 return getAllURITemplatesAdvancedThrottle(apiContext, version);
5688    } else {
5689  13 return getAllURITemplatesOldThrottle(apiContext, version);
5690    }
5691    }
5692   
 
5693  13 toggle public ArrayList<URITemplate> getAllURITemplatesOldThrottle(String apiContext, String version) throws APIManagementException {
5694  13 Connection connection = null;
5695  13 PreparedStatement prepStmt = null;
5696  13 ResultSet rs = null;
5697  13 ArrayList<URITemplate> uriTemplates = new ArrayList<URITemplate>();
5698   
5699    //TODO : FILTER RESULTS ONLY FOR ACTIVE APIs
5700  13 String query = SQLConstants.GET_ALL_URL_TEMPLATES_SQL;
5701  13 try {
5702  13 connection = APIMgtDBUtil.getConnection();
5703  13 prepStmt = connection.prepareStatement(query);
5704  13 prepStmt.setString(1, apiContext);
5705  13 prepStmt.setString(2, version);
5706   
5707  13 rs = prepStmt.executeQuery();
5708   
5709  13 URITemplate uriTemplate;
5710  54 while (rs.next()) {
5711  41 uriTemplate = new URITemplate();
5712  41 String script = null;
5713  41 uriTemplate.setHTTPVerb(rs.getString("HTTP_METHOD"));
5714  41 uriTemplate.setAuthType(rs.getString("AUTH_SCHEME"));
5715  41 uriTemplate.setUriTemplate(rs.getString("URL_PATTERN"));
5716  41 uriTemplate.setThrottlingTier(rs.getString("THROTTLING_TIER"));
5717  41 InputStream mediationScriptBlob = rs.getBinaryStream("MEDIATION_SCRIPT");
5718  41 if (mediationScriptBlob != null) {
5719  0 script = APIMgtDBUtil.getStringFromInputStream(mediationScriptBlob);
5720    }
5721  41 uriTemplate.setMediationScript(script);
5722  41 uriTemplate.getThrottlingConditions().add("_default");
5723  41 uriTemplates.add(uriTemplate);
5724    }
5725    } catch (SQLException e) {
5726  0 handleException("Error while fetching all URL Templates", e);
5727    } finally {
5728  13 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
5729    }
5730  13 return uriTemplates;
5731    }
5732   
 
5733  712 toggle public ArrayList<URITemplate> getAllURITemplatesAdvancedThrottle(String apiContext, String version) throws APIManagementException {
5734  712 Connection connection = null;
5735  712 PreparedStatement prepStmt = null;
5736  712 ResultSet rs = null;
5737  712 int tenantId;
5738  712 ArrayList<URITemplate> uriTemplates = new ArrayList<URITemplate>();
5739   
5740  712 String apiTenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(apiContext);
5741  712 if (apiTenantDomain != null) {
5742  202 tenantId = APIUtil.getTenantIdFromTenantDomain(apiTenantDomain);
5743    } else {
5744  510 tenantId = MultitenantConstants.SUPER_TENANT_ID;
5745    }
5746   
5747    // TODO : FILTER RESULTS ONLY FOR ACTIVE APIs
5748  712 String query = SQLConstants.ThrottleSQLConstants.GET_CONDITION_GROUPS_FOR_POLICIES_SQL;
5749  712 try {
5750  712 connection = APIMgtDBUtil.getConnection();
5751  712 prepStmt = connection.prepareStatement(query);
5752  712 prepStmt.setString(1, apiContext);
5753  712 prepStmt.setString(2, version);
5754  712 prepStmt.setInt(3, tenantId);
5755   
5756  712 rs = prepStmt.executeQuery();
5757  712 Map<String, Set<ConditionGroupDTO>> mapByHttpVerbURLPatternToId = new HashMap<String, Set<ConditionGroupDTO>>();
5758  1706 while (rs != null && rs.next()) {
5759   
5760  994 String httpVerb = rs.getString("HTTP_METHOD");
5761  994 String authType = rs.getString("AUTH_SCHEME");
5762  994 String urlPattern = rs.getString("URL_PATTERN");
5763  994 String policyName = rs.getString("THROTTLING_TIER");
5764  994 String conditionGroupId = rs.getString("CONDITION_GROUP_ID");
5765  994 String applicableLevel = rs.getString("APPLICABLE_LEVEL");
5766  994 String policyConditionGroupId = "_condition_" + conditionGroupId;
5767   
5768  994 String key = httpVerb + ":" + urlPattern;
5769  994 if (mapByHttpVerbURLPatternToId.containsKey(key)) {
5770  0 if (StringUtils.isEmpty(conditionGroupId)) {
5771  0 continue;
5772    }
5773   
5774    // Converting ConditionGroup to a lightweight ConditionGroupDTO.
5775  0 ConditionGroupDTO groupDTO = createConditionGroupDTO(Integer.parseInt(conditionGroupId));
5776  0 groupDTO.setConditionGroupId(policyConditionGroupId);
5777    // mapByHttpVerbURLPatternToId.get(key).add(policyConditionGroupId);
5778  0 mapByHttpVerbURLPatternToId.get(key).add(groupDTO);
5779   
5780    } else {
5781  994 String script = null;
5782  994 URITemplate uriTemplate = new URITemplate();
5783  994 uriTemplate.setThrottlingTier(policyName);
5784  994 uriTemplate.setAuthType(authType);
5785  994 uriTemplate.setHTTPVerb(httpVerb);
5786  994 uriTemplate.setUriTemplate(urlPattern);
5787  994 uriTemplate.setApplicableLevel(applicableLevel);
5788  994 InputStream mediationScriptBlob = rs.getBinaryStream("MEDIATION_SCRIPT");
5789  994 if (mediationScriptBlob != null) {
5790  0 script = APIMgtDBUtil.getStringFromInputStream(mediationScriptBlob);
5791    }
5792   
5793  994 uriTemplate.setMediationScript(script);
5794  994 Set<ConditionGroupDTO> conditionGroupIdSet = new HashSet<ConditionGroupDTO>();
5795  994 mapByHttpVerbURLPatternToId.put(key, conditionGroupIdSet);
5796  994 uriTemplates.add(uriTemplate);
5797  994 if (StringUtils.isEmpty(conditionGroupId)) {
5798  994 continue;
5799    }
5800  0 ConditionGroupDTO groupDTO = createConditionGroupDTO(Integer.parseInt(conditionGroupId));
5801  0 groupDTO.setConditionGroupId(policyConditionGroupId);
5802  0 conditionGroupIdSet.add(groupDTO);
5803   
5804    }
5805   
5806    }
5807   
5808  712 for (URITemplate uriTemplate : uriTemplates) {
5809  994 String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
5810  994 if (mapByHttpVerbURLPatternToId.containsKey(key)) {
5811  994 if (!mapByHttpVerbURLPatternToId.get(key).isEmpty()) {
5812  0 Set<ConditionGroupDTO> conditionGroupDTOs = mapByHttpVerbURLPatternToId.get(key);
5813  0 ConditionGroupDTO defaultGroup = new ConditionGroupDTO();
5814  0 defaultGroup.setConditionGroupId(APIConstants.THROTTLE_POLICY_DEFAULT);
5815  0 conditionGroupDTOs.add(defaultGroup);
5816    // uriTemplate.getThrottlingConditions().addAll(mapByHttpVerbURLPatternToId.get(key));
5817  0 uriTemplate.getThrottlingConditions().add(APIConstants.THROTTLE_POLICY_DEFAULT);
5818  0 uriTemplate.setConditionGroups(conditionGroupDTOs.toArray(new ConditionGroupDTO[]{}));
5819    }
5820   
5821    }
5822   
5823  994 if (uriTemplate.getThrottlingConditions().isEmpty()) {
5824  994 uriTemplate.getThrottlingConditions().add(APIConstants.THROTTLE_POLICY_DEFAULT);
5825  994 ConditionGroupDTO defaultGroup = new ConditionGroupDTO();
5826  994 defaultGroup.setConditionGroupId(APIConstants.THROTTLE_POLICY_DEFAULT);
5827  994 uriTemplate.setConditionGroups(new ConditionGroupDTO[]{defaultGroup});
5828    }
5829   
5830    }
5831    } catch (SQLException e) {
5832  0 handleException("Error while fetching all URL Templates", e);
5833    } finally {
5834  712 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
5835    }
5836  712 return uriTemplates;
5837    }
5838   
5839    /**
5840    * Converts an {@code Pipeline} object into a {@code ConditionGroupDTO}.{@code ConditionGroupDTO} class tries to
5841    * contain the same information held by {@code Pipeline}, but in a much lightweight fashion.
5842    *
5843    * @param conditionGroup Id of the condition group ({@code Pipeline}) to be converted
5844    * @return An object of {@code ConditionGroupDTO} type.
5845    * @throws APIManagementException
5846    */
 
5847  0 toggle private ConditionGroupDTO createConditionGroupDTO(int conditionGroup) throws APIManagementException {
5848  0 List<Condition> conditions = getConditions(conditionGroup);
5849  0 ArrayList<ConditionDTO> conditionDTOs = new ArrayList<ConditionDTO>(conditions.size());
5850  0 for (Condition condition : conditions) {
5851  0 ConditionDTO conditionDTO = new ConditionDTO();
5852  0 conditionDTO.setConditionType(condition.getType());
5853   
5854  0 conditionDTO.isInverted(condition.isInvertCondition());
5855  0 if (PolicyConstants.IP_RANGE_TYPE.equals(condition.getType())) {
5856  0 IPCondition ipRangeCondition = (IPCondition) condition;
5857  0 conditionDTO.setConditionName(ipRangeCondition.getStartingIP());
5858  0 conditionDTO.setConditionValue(ipRangeCondition.getEndingIP());
5859   
5860  0 } else if (PolicyConstants.IP_SPECIFIC_TYPE.equals(condition.getType())) {
5861  0 IPCondition ipCondition = (IPCondition) condition;
5862  0 conditionDTO.setConditionName(PolicyConstants.IP_SPECIFIC_TYPE);
5863  0 conditionDTO.setConditionValue(ipCondition.getSpecificIP());
5864   
5865  0 } else if (PolicyConstants.HEADER_TYPE.equals(condition.getType())) {
5866  0 HeaderCondition headerCondition = (HeaderCondition) condition;
5867  0 conditionDTO.setConditionName(headerCondition.getHeaderName());
5868  0 conditionDTO.setConditionValue(headerCondition.getValue());
5869   
5870  0 } else if (PolicyConstants.JWT_CLAIMS_TYPE.equals(condition.getType())) {
5871  0 JWTClaimsCondition jwtClaimsCondition = (JWTClaimsCondition) condition;
5872  0 conditionDTO.setConditionName(jwtClaimsCondition.getClaimUrl());
5873  0 conditionDTO.setConditionValue(jwtClaimsCondition.getAttribute());
5874   
5875  0 } else if (PolicyConstants.QUERY_PARAMETER_TYPE.equals(condition.getType())) {
5876  0 QueryParameterCondition parameterCondition = (QueryParameterCondition) condition;
5877  0 conditionDTO.setConditionName(parameterCondition.getParameter());
5878  0 conditionDTO.setConditionValue(parameterCondition.getValue());
5879    }
5880  0 conditionDTOs.add(conditionDTO);
5881    }
5882   
5883  0 ConditionGroupDTO conditionGroupDTO = new ConditionGroupDTO();
5884  0 conditionGroupDTO.setConditions(conditionDTOs.toArray(new ConditionDTO[]{}));
5885   
5886  0 return conditionGroupDTO;
5887    }
5888   
5889   
 
5890  66 toggle public void updateAPI(API api, int tenantId) throws APIManagementException {
5891  66 Connection connection = null;
5892  66 PreparedStatement prepStmt = null;
5893   
5894  66 String previousDefaultVersion = getDefaultVersion(api.getId());
5895   
5896  66 String query = SQLConstants.UPDATE_API_SQL;
5897  66 try {
5898  66 connection = APIMgtDBUtil.getConnection();
5899  66 connection.setAutoCommit(false);
5900    //Header change check not required here as we update API level throttling tier
5901    //from same call.
5902    //TODO review and run tier update as separate query if need.
5903  66 prepStmt = connection.prepareStatement(query);
5904  66 prepStmt.setString(1, api.getContext());
5905  66 String contextTemplate = api.getContextTemplate();
5906    //If the context template ends with {version} this means that the version will be at the end of the
5907    // context.
5908  66 if (contextTemplate.endsWith("/" + APIConstants.VERSION_PLACEHOLDER)) {
5909    //Remove the {version} part from the context template.
5910  62 contextTemplate = contextTemplate.split(Pattern.quote("/" + APIConstants.VERSION_PLACEHOLDER))[0];
5911    }
5912  66 prepStmt.setString(2, contextTemplate);
5913    //TODO Need to find who exactly does this update.
5914  66 prepStmt.setString(3, null);
5915  66 prepStmt.setTimestamp(4, new Timestamp(System.currentTimeMillis()));
5916  66 prepStmt.setString(5, api.getApiLevelPolicy());
5917  66 prepStmt.setString(6, APIUtil.replaceEmailDomainBack(api.getId().getProviderName()));
5918  66 prepStmt.setString(7, api.getId().getApiName());
5919  66 prepStmt.setString(8, api.getId().getVersion());
5920  66 prepStmt.execute();
5921    //}
5922   
5923  66 if (api.isDefaultVersion() ^ api.getId().getVersion().equals(previousDefaultVersion)) { //A change has
5924    // happen
5925    //If the api is selected as default version, it is added/replaced into AM_API_DEFAULT_VERSION table
5926  0 if (api.isDefaultVersion()) {
5927  0 addUpdateAPIAsDefaultVersion(api, connection);
5928    } else { //tick is removed
5929  0 removeAPIFromDefaultVersion(api.getId(), connection);
5930    }
5931    }
5932  66 connection.commit();
5933   
5934  66 updateScopes(api, tenantId);
5935  66 updateURLTemplates(api);
5936    } catch (SQLException e) {
5937  0 handleException("Error while updating the API: " + api.getId() + " in the database", e);
5938    } finally {
5939  66 APIMgtDBUtil.closeAllConnections(prepStmt, connection, null);
5940    }
5941    }
5942   
 
5943  14012 toggle public int getAPIID(APIIdentifier apiId, Connection connection) throws APIManagementException {
5944  14012 boolean created = false;
5945  14012 PreparedStatement prepStmt = null;
5946  14012 ResultSet rs = null;
5947   
5948  14012 int id = -1;
5949  14012 String getAPIQuery = SQLConstants.GET_API_ID_SQL;
5950   
5951  14012 try {
5952  14012 if (connection == null) {
5953   
5954    // If connection is not provided a new one will be created.
5955  7249 connection = APIMgtDBUtil.getConnection();
5956  7249 created = true;
5957    }
5958   
5959  14012 prepStmt = connection.prepareStatement(getAPIQuery);
5960  14012 prepStmt.setString(1, APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
5961  14012 prepStmt.setString(2, apiId.getApiName());
5962  14012 prepStmt.setString(3, apiId.getVersion());
5963  14012 rs = prepStmt.executeQuery();
5964  14012 if (rs.next()) {
5965  14005 id = rs.getInt("API_ID");
5966    }
5967  14012 if (id == -1) {
5968  7 String msg = "Unable to find the API: " + apiId + " in the database";
5969  7 log.error(msg);
5970  7 throw new APIManagementException(msg);
5971    }
5972    } catch (SQLException e) {
5973  0 handleException("Error while locating API: " + apiId + " from the database", e);
5974    } finally {
5975  14012 if (created) {
5976  7249 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
5977    } else {
5978  6763 APIMgtDBUtil.closeAllConnections(prepStmt, null, rs);
5979    }
5980    }
5981  14005 return id;
5982    }
5983   
5984    /**
5985    * Delete a record from AM_APPLICATION_KEY_MAPPING table
5986    *
5987    * @param consumerKey
5988    * @throws APIManagementException
5989    */
 
5990  0 toggle public void deleteApplicationMappingByConsumerKey(String consumerKey) throws APIManagementException {
5991  0 Connection connection = null;
5992  0 PreparedStatement prepStmt = null;
5993   
5994  0 String deleteApplicationKeyQuery = SQLConstants.REMOVE_APPLICATION_MAPPINGS_BY_CONSUMER_KEY_SQL;
5995  0 try {
5996  0 connection = APIMgtDBUtil.getConnection();
5997  0 connection.setAutoCommit(false);
5998  0 prepStmt = connection.prepareStatement(deleteApplicationKeyQuery);
5999  0 prepStmt.setString(1, consumerKey);
6000  0 prepStmt.execute();
6001  0 connection.commit();
6002    } catch (SQLException e) {
6003  0 handleException("Error while deleting mapping: consumer key " + consumerKey + " from the database", e);
6004    } finally {
6005  0 APIMgtDBUtil.closeAllConnections(prepStmt, connection, null);
6006    }
6007    }
6008   
 
6009  259 toggle public void deleteAPI(APIIdentifier apiId) throws APIManagementException {
6010  259 Connection connection = null;
6011  259 PreparedStatement prepStmt = null;
6012  259 int id;
6013   
6014  259 String deleteLCEventQuery = SQLConstants.REMOVE_FROM_API_LIFECYCLE_SQL;
6015  259 String deleteCommentQuery = SQLConstants.REMOVE_FROM_API_COMMENT_SQL;
6016  259 String deleteRatingsQuery = SQLConstants.REMOVE_FROM_API_RATING_SQL;
6017  259 String deleteSubscriptionQuery = SQLConstants.REMOVE_FROM_API_SUBSCRIPTION_SQL;
6018  259 String deleteExternalAPIStoresQuery = SQLConstants.REMOVE_FROM_EXTERNAL_STORES_SQL;
6019  259 String deleteAPIQuery = SQLConstants.REMOVE_FROM_API_SQL;
6020  259 String deleteURLTemplateQuery = SQLConstants.REMOVE_FROM_API_URL_MAPPINGS_SQL;
6021   
6022  259 try {
6023  259 connection = APIMgtDBUtil.getConnection();
6024  259 connection.setAutoCommit(false);
6025   
6026  259 id = getAPIID(apiId, connection);
6027   
6028  259 removeAPIScope(apiId);
6029   
6030  259 prepStmt = connection.prepareStatement(deleteSubscriptionQuery);
6031  259 prepStmt.setInt(1, id);
6032  259 prepStmt.execute();
6033  259 prepStmt.close();//If exception occurs at execute, this statement will close in finally else here
6034   
6035    //Delete all comments associated with given API
6036  259 prepStmt = connection.prepareStatement(deleteCommentQuery);
6037  259 prepStmt.setInt(1, id);
6038  259 prepStmt.execute();
6039  259 prepStmt.close();//If exception occurs at execute, this statement will close in finally else here
6040   
6041  259 prepStmt = connection.prepareStatement(deleteRatingsQuery);
6042  259 prepStmt.setInt(1, id);
6043  259 prepStmt.execute();
6044  259 prepStmt.close();//If exception occurs at execute, this statement will close in finally else here
6045   
6046  259 prepStmt = connection.prepareStatement(deleteLCEventQuery);
6047  259 prepStmt.setInt(1, id);
6048  259 prepStmt.execute();
6049  259 prepStmt.close();//If exception occurs at execute, this statement will close in finally else here
6050   
6051    //Delete all external APIStore details associated with a given API
6052  259 prepStmt = connection.prepareStatement(deleteExternalAPIStoresQuery);
6053  259 prepStmt.setInt(1, id);
6054  259 prepStmt.execute();
6055  259 prepStmt.close();//If exception occurs at execute, this statement will close in finally else here
6056   
6057  259 prepStmt = connection.prepareStatement(deleteAPIQuery);
6058  259 prepStmt.setString(1, APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
6059  259 prepStmt.setString(2, apiId.getApiName());
6060  259 prepStmt.setString(3, apiId.getVersion());
6061  259 prepStmt.execute();
6062  259 prepStmt.close();//If exception occurs at execute, this statement will close in finally else here
6063   
6064  259 prepStmt = connection.prepareStatement(deleteURLTemplateQuery);
6065  259 prepStmt.setInt(1, id);
6066  259 prepStmt.execute();
6067   
6068  259 String curDefaultVersion = getDefaultVersion(apiId);
6069  259 String pubDefaultVersion = getPublishedDefaultVersion(apiId);
6070  259 if (apiId.getVersion().equals(curDefaultVersion)) {
6071  21 removeAPIFromDefaultVersion(apiId, connection);
6072  238 } else if (apiId.getVersion().equals(pubDefaultVersion)) {
6073  0 setPublishedDefVersion(apiId, connection, null);
6074    }
6075   
6076  259 connection.commit();
6077    } catch (SQLException e) {
6078  0 handleException("Error while removing the API: " + apiId + " from the database", e);
6079    } finally {
6080  259 APIMgtDBUtil.closeAllConnections(prepStmt, connection, null);
6081    }
6082    }
6083   
6084    /**
6085    * Change access token status in to revoked in database level.
6086    *
6087    * @param key API Key to be revoked
6088    * @throws APIManagementException on error in revoking access token
6089    */
 
6090  2 toggle public void revokeAccessToken(String key) throws APIManagementException {
6091  2 String accessTokenStoreTable = APIConstants.ACCESS_TOKEN_STORE_TABLE;
6092  2 accessTokenStoreTable = getAccessTokenStoreTableFromAccessToken(key, accessTokenStoreTable);
6093  2 Connection conn = null;
6094  2 PreparedStatement ps = null;
6095  2 try {
6096  2 conn = APIMgtDBUtil.getConnection();
6097  2 conn.setAutoCommit(false);
6098   
6099  2 String query = SQLConstants.REMOVE_ACCESS_TOKEN_PREFIX + accessTokenStoreTable + SQLConstants
6100    .REVOKE_ACCESS_TOKEN_SUFFIX;
6101  2 ps = conn.prepareStatement(query);
6102  2 ps.setString(1, APIUtil.encryptToken(key));
6103  2 ps.execute();
6104   
6105  2 conn.commit();
6106    } catch (SQLException e) {
6107  0 handleException("Error in revoking access token: " + e.getMessage(), e);
6108    } catch (CryptoException e) {
6109  0 handleException("Error in revoking access token: " + e.getMessage(), e);
6110    } finally {
6111  2 APIMgtDBUtil.closeAllConnections(ps, conn, null);
6112    }
6113    }
6114   
6115   
6116    /**
6117    * Get all applications associated with given tier
6118    *
6119    * @param tier String tier name
6120    * @return Application object array associated with tier
6121    * @throws APIManagementException on error in getting applications array
6122    */
 
6123  0 toggle public Application[] getApplicationsByTier(String tier) throws APIManagementException {
6124  0 if (tier == null) {
6125  0 return null;
6126    }
6127  0 Connection connection = null;
6128  0 PreparedStatement prepStmt = null;
6129  0 ResultSet rs = null;
6130  0 Application[] applications = null;
6131   
6132  0 String sqlQuery = SQLConstants.GET_APPLICATION_BY_TIER_SQL;
6133  0 try {
6134  0 connection = APIMgtDBUtil.getConnection();
6135  0 prepStmt = connection.prepareStatement(sqlQuery);
6136  0 prepStmt.setString(1, tier);
6137  0 rs = prepStmt.executeQuery();
6138  0 ArrayList<Application> applicationsList = new ArrayList<Application>();
6139  0 Application application;
6140  0 while (rs.next()) {
6141  0 application = new Application(rs.getString("NAME"), getSubscriber(rs.getString("SUBSCRIBER_ID")));
6142  0 application.setId(rs.getInt("APPLICATION_ID"));
6143  0 applicationsList.add(application);
6144    }
6145  0 Collections.sort(applicationsList, new Comparator<Application>() {
 
6146  0 toggle public int compare(Application o1, Application o2) {
6147  0 return o1.getName().compareToIgnoreCase(o2.getName());
6148    }
6149    });
6150  0 applications = applicationsList.toArray(new Application[applicationsList.size()]);
6151   
6152    } catch (SQLException e) {
6153  0 handleException("Error when reading the application information from" + " the persistence store.", e);
6154    } finally {
6155  0 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
6156    }
6157  0 return applications;
6158    }
6159   
 
6160  0 toggle private void handleException(String msg, Throwable t) throws APIManagementException {
6161  0 log.error(msg, t);
6162  0 throw new APIManagementException(msg, t);
6163    }
6164   
6165   
 
6166  2880 toggle public HashMap<String, String> getURITemplatesPerAPIAsString(APIIdentifier identifier)
6167    throws APIManagementException {
6168  2880 Connection conn = null;
6169  2880 ResultSet resultSet = null;
6170  2880 PreparedStatement ps = null;
6171  2880 int apiId;
6172  2880 HashMap<String, String> urlMappings = new LinkedHashMap<String, String>();
6173  2880 try {
6174  2880 conn = APIMgtDBUtil.getConnection();
6175  2880 apiId = getAPIID(identifier, conn);
6176   
6177  2880 String sqlQuery = SQLConstants.GET_URL_TEMPLATES_SQL;
6178   
6179  2880 ps = conn.prepareStatement(sqlQuery);
6180  2880 ps.setInt(1, apiId);
6181  2880 resultSet = ps.executeQuery();
6182  7580 while (resultSet.next()) {
6183  4700 String script = null;
6184  4700 String uriPattern = resultSet.getString("URL_PATTERN");
6185  4700 String httpMethod = resultSet.getString("HTTP_METHOD");
6186  4700 String authScheme = resultSet.getString("AUTH_SCHEME");
6187  4700 String throttlingTier = resultSet.getString("THROTTLING_TIER");
6188  4700 InputStream mediationScriptBlob = resultSet.getBinaryStream("MEDIATION_SCRIPT");
6189  4700 if (mediationScriptBlob != null) {
6190  48 script = APIMgtDBUtil.getStringFromInputStream(mediationScriptBlob);
6191    // set null if the script is empty. Otherwise ArrayIndexOutOfBoundsException occurs when trying
6192    // to split by ::
6193  48 if (script.isEmpty()) {
6194  0 script = null;
6195    }
6196    }
6197  4700 urlMappings.put(uriPattern + "::" + httpMethod + "::" + authScheme + "::" + throttlingTier + "::" +
6198    script, null);
6199    }
6200    } catch (SQLException e) {
6201  0 if (conn != null) {
6202  0 try {
6203  0 conn.rollback();
6204    } catch (SQLException e1) {
6205  0 log.error("Failed to rollback the add subscription ", e1);
6206    }
6207    }
6208  0 handleException("Failed to add subscriber data ", e);
6209    } finally {
6210  2880 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
6211    }
6212  2880 return urlMappings;
6213    }
6214   
6215    // This should be only used only when Token Partitioning is enabled.
 
6216  0 toggle public String getConsumerKeyForTokenWhenTokenPartitioningEnabled(String accessToken) throws APIManagementException {
6217   
6218  0 if (APIUtil.checkAccessTokenPartitioningEnabled() && APIUtil.checkUserNameAssertionEnabled()) {
6219  0 String accessTokenStoreTable = APIUtil.getAccessTokenStoreTableFromAccessToken(accessToken);
6220  0 StringBuilder authorizedDomains = new StringBuilder();
6221  0 String getCKFromTokenSQL = "SELECT CONSUMER_KEY " +
6222    " FROM " + accessTokenStoreTable +
6223    " WHERE ACCESS_TOKEN = ? ";
6224   
6225  0 Connection connection = null;
6226  0 PreparedStatement prepStmt = null;
6227  0 ResultSet rs = null;
6228  0 try {
6229  0 connection = APIMgtDBUtil.getConnection();
6230  0 prepStmt = connection.prepareStatement(getCKFromTokenSQL);
6231  0 prepStmt.setString(1, APIUtil.encryptToken(accessToken));
6232  0 rs = prepStmt.executeQuery();
6233  0 boolean first = true;
6234  0 while (rs.next()) {
6235  0 String domain = rs.getString(1);
6236  0 if (first) {
6237  0 authorizedDomains.append(domain);
6238  0 first = false;
6239    } else {
6240  0 authorizedDomains.append(',').append(domain);
6241    }
6242    }
6243    } catch (SQLException e) {
6244  0 throw new APIManagementException("Error in retrieving access allowing domain list from table.", e);
6245    } catch (CryptoException e) {
6246  0 throw new APIManagementException("Error in retrieving access allowing domain list from table.", e);
6247    } finally {
6248  0 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
6249    }
6250  0 return authorizedDomains.toString();
6251    }
6252  0 return null;
6253    }
6254   
 
6255  0 toggle public String findConsumerKeyFromAccessToken(String accessToken) throws APIManagementException {
6256  0 String accessTokenStoreTable = APIConstants.ACCESS_TOKEN_STORE_TABLE;
6257  0 accessTokenStoreTable = getAccessTokenStoreTableFromAccessToken(accessToken, accessTokenStoreTable);
6258  0 Connection connection = null;
6259  0 PreparedStatement smt = null;
6260  0 ResultSet rs = null;
6261  0 String consumerKey = null;
6262  0 try {
6263  0 String getConsumerKeySql = SQLConstants.GET_CONSUMER_KEY_BY_ACCESS_TOKEN_PREFIX + accessTokenStoreTable +
6264    SQLConstants.GET_CONSUMER_KEY_BY_ACCESS_TOKEN_SUFFIX;
6265  0 connection = APIMgtDBUtil.getConnection();
6266  0 smt = connection.prepareStatement(getConsumerKeySql);
6267  0 smt.setString(1, APIUtil.encryptToken(accessToken));
6268  0 rs = smt.executeQuery();
6269  0 while (rs.next()) {
6270  0 consumerKey = rs.getString(1);
6271    }
6272    } catch (SQLException e) {
6273  0 handleException("Error while getting authorized domians.", e);
6274    } catch (CryptoException e) {
6275  0 handleException("Error while getting authorized domians.", e);
6276    } finally {
6277  0 APIMgtDBUtil.closeAllConnections(smt, connection, rs);
6278    }
6279  0 return consumerKey;
6280    }
6281   
6282    /**
6283    * Adds a comment for an API
6284    *
6285    * @param identifier API Identifier
6286    * @param commentText Commented Text
6287    * @param user User who did the comment
6288    * @return Comment ID
6289    */
 
6290  2 toggle public int addComment(APIIdentifier identifier, String commentText, String user) throws APIManagementException {
6291   
6292  2 Connection connection = null;
6293  2 ResultSet resultSet = null;
6294  2 ResultSet insertSet = null;
6295  2 PreparedStatement getPrepStmt = null;
6296  2 PreparedStatement insertPrepStmt = null;
6297  2 int commentId = -1;
6298  2 int apiId = -1;
6299   
6300  2 try {
6301  2 connection = APIMgtDBUtil.getConnection();
6302  2 connection.setAutoCommit(false);
6303   
6304  2 String getApiQuery = SQLConstants.GET_API_ID_SQL;
6305  2 getPrepStmt = connection.prepareStatement(getApiQuery);
6306  2 getPrepStmt.setString(1, APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
6307  2 getPrepStmt.setString(2, identifier.getApiName());
6308  2 getPrepStmt.setString(3, identifier.getVersion());
6309  2 resultSet = getPrepStmt.executeQuery();
6310  2 if (resultSet.next()) {
6311  2 apiId = resultSet.getInt("API_ID");
6312    }
6313   
6314  2 if (apiId == -1) {
6315  0 String msg = "Unable to get the API ID for: " + identifier;
6316  0 log.error(msg);
6317  0 throw new APIManagementException(msg);
6318    }
6319   
6320    /*This query to update the AM_API_COMMENTS table */
6321  2 String addCommentQuery = SQLConstants.ADD_COMMENT_SQL;
6322   
6323    /*Adding data to the AM_API_COMMENTS table*/
6324  2 String dbProductName = connection.getMetaData().getDatabaseProductName();
6325  2 insertPrepStmt = connection.prepareStatement(addCommentQuery,
6326    new String[]{DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "comment_id")});
6327   
6328  2 insertPrepStmt.setString(1, commentText);
6329  2 insertPrepStmt.setString(2, user);
6330  2 insertPrepStmt.setTimestamp(3, new Timestamp(System.currentTimeMillis()), Calendar.getInstance());
6331  2 insertPrepStmt.setInt(4, apiId);
6332   
6333  2 insertPrepStmt.executeUpdate();
6334  2 insertSet = insertPrepStmt.getGeneratedKeys();
6335  4 while (insertSet.next()) {
6336  2 commentId = Integer.parseInt(insertSet.getString(1));
6337    }
6338  2 connection.commit();
6339    } catch (SQLException e) {
6340  0 if (connection != null) {
6341  0 try {
6342  0 connection.rollback();
6343    } catch (SQLException e1) {
6344  0 log.error("Failed to rollback the add comment ", e1);
6345    }
6346    }
6347  0 handleException("Failed to add comment data, for " + identifier.getApiName() + '-' + identifier
6348    .getVersion(), e);
6349    } finally {
6350  2 APIMgtDBUtil.closeAllConnections(getPrepStmt, connection, resultSet);
6351  2 APIMgtDBUtil.closeAllConnections(insertPrepStmt, null, insertSet);
6352    }
6353  2 return commentId;
6354    }
6355   
6356    /**
6357    * Returns all the Comments on an API
6358    *
6359    * @param identifier API Identifier
6360    * @return Comment Array
6361    * @throws APIManagementException
6362    */
 
6363  10 toggle public Comment[] getComments(APIIdentifier identifier) throws APIManagementException {
6364  10 List<Comment> commentList = new ArrayList<Comment>();
6365  10 Connection connection = null;
6366  10 ResultSet resultSet = null;
6367  10 PreparedStatement prepStmt = null;
6368   
6369  10 String sqlQuery = SQLConstants.GET_COMMENTS_SQL;
6370  10 try {
6371  10 connection = APIMgtDBUtil.getConnection();
6372  10 prepStmt = connection.prepareStatement(sqlQuery);
6373  10 prepStmt.setString(1, APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
6374  10 prepStmt.setString(2, identifier.getApiName());
6375  10 prepStmt.setString(3, identifier.getVersion());
6376  10 resultSet = prepStmt.executeQuery();
6377  10 while (resultSet.next()) {
6378  0 Comment comment = new Comment();
6379  0 comment.setText(resultSet.getString("COMMENT_TEXT"));
6380  0 comment.setUser(resultSet.getString("COMMENTED_USER"));
6381  0 comment.setCreatedTime(new java.util.Date(resultSet.getTimestamp("DATE_COMMENTED").getTime()));
6382  0 commentList.add(comment);
6383    }
6384    } catch (SQLException e) {
6385  0 try {
6386  0 if (connection != null) {
6387  0 connection.rollback();
6388    }
6389    } catch (SQLException e1) {
6390  0 log.error("Failed to retrieve comments ", e1);
6391    }
6392  0 handleException("Failed to retrieve comments for " + identifier.getApiName() + '-' + identifier
6393    .getVersion(), e);
6394    } finally {
6395  10 APIMgtDBUtil.closeAllConnections(prepStmt, connection, resultSet);
6396    }
6397  10 return commentList.toArray(new Comment[commentList.size()]);
6398    }
6399   
 
6400  0 toggle public boolean isContextExist(String context) {
6401  0 Connection connection = null;
6402  0 ResultSet resultSet = null;
6403  0 PreparedStatement prepStmt = null;
6404   
6405  0 String sql = SQLConstants.GET_API_CONTEXT_SQL;
6406  0 try {
6407  0 connection = APIMgtDBUtil.getConnection();
6408  0 prepStmt = connection.prepareStatement(sql);
6409  0 prepStmt.setString(1, context);
6410  0 resultSet = prepStmt.executeQuery();
6411   
6412  0 while (resultSet.next()) {
6413  0 if (resultSet.getString(1) != null) {
6414  0 return true;
6415    }
6416    }
6417    } catch (SQLException e) {
6418  0 log.error("Failed to retrieve the API Context ", e);
6419    } finally {
6420  0 APIMgtDBUtil.closeAllConnections(prepStmt, connection, resultSet);
6421    }
6422  0 return false;
6423    }
6424   
 
6425  259 toggle public String getAPIContext(APIIdentifier identifier) throws APIManagementException {
6426  259 Connection connection = null;
6427  259 ResultSet resultSet = null;
6428  259 PreparedStatement prepStmt = null;
6429   
6430  259 String context = null;
6431   
6432  259 String sql = SQLConstants.GET_API_CONTEXT_BY_API_NAME_SQL;
6433  259 try {
6434  259 connection = APIMgtDBUtil.getConnection();
6435  259 prepStmt = connection.prepareStatement(sql);
6436  259 prepStmt.setString(1, APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
6437  259 prepStmt.setString(2, identifier.getApiName());
6438  259 prepStmt.setString(3, identifier.getVersion());
6439  259 resultSet = prepStmt.executeQuery();
6440   
6441  518 while (resultSet.next()) {
6442  259 context = resultSet.getString(1);
6443    }
6444    } catch (SQLException e) {
6445  0 log.error("Failed to retrieve the API Context", e);
6446   
6447  0 handleException("Failed to retrieve the API Context for " +
6448    identifier.getProviderName() + '-' + identifier.getApiName() + '-' + identifier
6449    .getVersion(), e);
6450    } finally {
6451  259 APIMgtDBUtil.closeAllConnections(prepStmt, connection, resultSet);
6452    }
6453  259 return context;
6454    }
6455   
 
6456  18 toggle public List<String> getAllAvailableContexts() {
6457  18 List<String> contexts = new ArrayList<String>();
6458  18 Connection connection = null;
6459  18 ResultSet resultSet = null;
6460  18 PreparedStatement prepStmt = null;
6461   
6462  18 String sql = SQLConstants.GET_ALL_CONTEXT_SQL;
6463  18 try {
6464  18 connection = APIMgtDBUtil.getConnection();
6465  18 prepStmt = connection.prepareStatement(sql);
6466  18 resultSet = prepStmt.executeQuery();
6467   
6468  190 while (resultSet.next()) {
6469  172 contexts.add(resultSet.getString("CONTEXT"));
6470    }
6471    } catch (SQLException e) {
6472  0 log.error("Failed to retrieve the API Context ", e);
6473    } finally {
6474  18 APIMgtDBUtil.closeAllConnections(prepStmt, connection, resultSet);
6475    }
6476  18 return contexts;
6477    }
6478   
 
6479  0 toggle public void populateAppRegistrationWorkflowDTO(ApplicationRegistrationWorkflowDTO workflowDTO)
6480    throws APIManagementException {
6481  0 Connection conn = null;
6482  0 PreparedStatement ps = null;
6483  0 ResultSet rs = null;
6484  0 Application application = null;
6485  0 Subscriber subscriber = null;
6486   
6487  0 String registrationEntry = SQLConstants.GET_APPLICATION_REGISTRATION_ENTRY_BY_SUBSCRIBER_SQL;
6488  0 try {
6489  0 conn = APIMgtDBUtil.getConnection();
6490  0 ps = conn.prepareStatement(registrationEntry);
6491  0 ps.setString(1, workflowDTO.getExternalWorkflowReference());
6492  0 rs = ps.executeQuery();
6493   
6494  0 while (rs.next()) {
6495  0 subscriber = new Subscriber(rs.getString("USER_ID"));
6496  0 subscriber.setId(rs.getInt("SUBSCRIBER_ID"));
6497  0 application = new Application(rs.getString("NAME"), subscriber);
6498  0 application.setId(rs.getInt("APPLICATION_ID"));
6499  0 application.setApplicationWorkFlowStatus(rs.getString("APPLICATION_STATUS"));
6500  0 application.setCallbackUrl(rs.getString("CALLBACK_URL"));
6501  0 application.setDescription(rs.getString("DESCRIPTION"));
6502  0 application.setTier(rs.getString("APPLICATION_TIER"));
6503  0 workflowDTO.setApplication(application);
6504  0 workflowDTO.setKeyType(rs.getString("TOKEN_TYPE"));
6505  0 workflowDTO.setUserName(subscriber.getName());
6506  0 workflowDTO.setDomainList(rs.getString("ALLOWED_DOMAINS"));
6507  0 workflowDTO.setValidityTime(rs.getLong("VALIDITY_PERIOD"));
6508  0 OAuthAppRequest request = ApplicationUtils.createOauthAppRequest(application.getName(), null,
6509    application.getCallbackUrl(), rs
6510    .getString("TOKEN_SCOPE"),
6511    rs.getString("INPUTS"), application.getTokenType());
6512  0 workflowDTO.setAppInfoDTO(request);
6513    }
6514    } catch (SQLException e) {
6515  0 handleException("Error occurred while retrieving an " +
6516    "Application Registration Entry for Workflow : " + workflowDTO
6517    .getExternalWorkflowReference(), e);
6518    } finally {
6519  0 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
6520    }
6521    }
6522   
 
6523  0 toggle public int getApplicationIdForAppRegistration(String workflowReference) throws APIManagementException {
6524   
6525  0 Connection conn = null;
6526  0 PreparedStatement ps = null;
6527  0 ResultSet rs = null;
6528  0 int appId = -1;
6529   
6530  0 String registrationEntry = SQLConstants.GET_APPLICATION_REGISTRATION_ID_SQL;
6531  0 try {
6532  0 conn = APIMgtDBUtil.getConnection();
6533  0 ps = conn.prepareStatement(registrationEntry);
6534  0 ps.setString(1, workflowReference);
6535  0 rs = ps.executeQuery();
6536   
6537  0 while (rs.next()) {
6538  0 appId = rs.getInt("APP_ID");
6539    }
6540    } catch (SQLException e) {
6541  0 handleException("Error occurred while retrieving an " +
6542    "Application Registration Entry for Workflow : " + workflowReference, e);
6543    } finally {
6544  0 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
6545    }
6546  0 return appId;
6547    }
6548   
6549    /**
6550    * Fetches WorkflowReference when given Application Name and UserId.
6551    *
6552    * @param applicationName
6553    * @param userId
6554    * @return WorkflowReference
6555    * @throws APIManagementException
6556    */
 
6557  0 toggle public String getWorkflowReference(String applicationName, String userId) throws APIManagementException {
6558  0 Connection conn = null;
6559  0 PreparedStatement ps = null;
6560  0 ResultSet rs = null;
6561  0 String workflowReference = null;
6562   
6563  0 String sqlQuery = SQLConstants.GET_WORKFLOW_ENTRY_SQL;
6564  0 try {
6565  0 conn = APIMgtDBUtil.getConnection();
6566  0 ps = conn.prepareStatement(sqlQuery);
6567  0 ps.setString(1, applicationName);
6568  0 ps.setString(2, userId);
6569  0 rs = ps.executeQuery();
6570   
6571  0 while (rs.next()) {
6572  0 workflowReference = rs.getString("WF_REF");
6573    }
6574    } catch (SQLException e) {
6575  0 handleException("Error occurred while getting workflow entry for " +
6576    "Application : " + applicationName + " created by " + userId, e);
6577    } finally {
6578  0 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
6579    }
6580  0 return workflowReference;
6581    }
6582   
6583    /**
6584    * Retries the WorkflowExternalReference for a application.
6585    *
6586    * @param appID ID of the application
6587    * @return External workflow reference for the application identified
6588    * @throws APIManagementException
6589    */
 
6590  130 toggle public String getExternalWorkflowReferenceByApplicationID(int appID) throws APIManagementException {
6591  130 String workflowExtRef = null;
6592  130 Connection conn = null;
6593  130 PreparedStatement ps = null;
6594  130 ResultSet rs = null;
6595   
6596  130 String sqlQuery = SQLConstants.GET_EXTERNAL_WORKFLOW_REFERENCE_SQL;
6597  130 try {
6598  130 conn = APIMgtDBUtil.getConnection();
6599  130 ps = conn.prepareStatement(sqlQuery);
6600  130 ps.setString(1, WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION);
6601  130 ps.setString(2, String.valueOf(appID));
6602  130 rs = ps.executeQuery();
6603   
6604    // returns only one row
6605  130 while (rs.next()) {
6606  0 workflowExtRef = rs.getString("WF_EXTERNAL_REFERENCE");
6607    }
6608    } catch (SQLException e) {
6609  0 handleException("Error occurred while getting workflow entry for " +
6610    "Application ID : " + appID, e);
6611    } finally {
6612  130 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
6613    }
6614   
6615  130 return workflowExtRef;
6616    }
6617   
6618    /**
6619    * Remove workflow entry
6620    *
6621    * @param workflowReference
6622    * @param workflowType
6623    * @throws APIManagementException
6624    */
 
6625  0 toggle public void removeWorkflowEntry(String workflowReference, String workflowType) throws APIManagementException {
6626   
6627  0 Connection connection = null;
6628  0 PreparedStatement prepStmt = null;
6629   
6630  0 String queryWorkflowDelete = SQLConstants.REMOVE_WORKFLOW_ENTRY_SQL;
6631  0 try {
6632  0 connection = APIMgtDBUtil.getConnection();
6633  0 connection.setAutoCommit(false);
6634  0 prepStmt = connection.prepareStatement(queryWorkflowDelete);
6635  0 prepStmt.setString(1, workflowType);
6636  0 prepStmt.setString(2, workflowReference);
6637  0 prepStmt.execute();
6638  0 connection.commit();
6639    } catch (SQLException e) {
6640  0 handleException("Error while deleting workflow entry " + workflowReference + " from the database", e);
6641    } finally {
6642  0 APIMgtDBUtil.closeAllConnections(prepStmt, connection, null);
6643    }
6644    }
6645   
6646    /**
6647    * Retries the WorkflowExternalReference for a subscription.
6648    *
6649    * @param identifier APIIdentifier to find the subscribed api
6650    * @param appID ID of the application which has the subscription
6651    * @return External workflow reference for the subscription identified
6652    * @throws APIManagementException
6653    */
 
6654  63 toggle public String getExternalWorkflowReferenceForSubscription(APIIdentifier identifier, int appID)
6655    throws APIManagementException {
6656  63 String workflowExtRef = null;
6657  63 Connection conn = null;
6658  63 PreparedStatement ps = null;
6659  63 ResultSet rs = null;
6660  63 int apiID;
6661  63 int subscriptionID = -1;
6662   
6663  63 String sqlQuery = SQLConstants.GET_EXTERNAL_WORKFLOW_REFERENCE_FOR_SUBSCRIPTION_SQL;
6664  63 String postgreSQL = SQLConstants.GET_EXTERNAL_WORKFLOW_REFERENCE_FOR_SUBSCRIPTION_POSTGRE_SQL;
6665  63 try {
6666  63 apiID = getAPIID(identifier, conn);
6667  63 conn = APIMgtDBUtil.getConnection();
6668  63 if (conn.getMetaData().getDriverName().contains("PostgreSQL")) {
6669  0 sqlQuery = postgreSQL;
6670    }
6671  63 ps = conn.prepareStatement(sqlQuery);
6672  63 ps.setInt(1, apiID);
6673  63 ps.setInt(2, appID);
6674  63 ps.setString(3, WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
6675  63 rs = ps.executeQuery();
6676   
6677    // returns only one row
6678  64 while (rs.next()) {
6679  1 workflowExtRef = rs.getString("WF_EXTERNAL_REFERENCE");
6680    }
6681   
6682    } catch (SQLException e) {
6683  0 handleException("Error occurred while getting workflow entry for " +
6684    "Subscription : " + subscriptionID, e);
6685    } finally {
6686  63 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
6687    }
6688   
6689  63 return workflowExtRef;
6690    }
6691   
6692    /**
6693    * Retries the WorkflowExternalReference for a subscription.
6694    *
6695    * @param subscriptionId ID of the subscription
6696    * @return External workflow reference for the subscription <code>subscriptionId</code>
6697    * @throws APIManagementException
6698    */
 
6699  1 toggle public String getExternalWorkflowReferenceForSubscription(int subscriptionId) throws APIManagementException {
6700  1 String workflowExtRef = null;
6701  1 Connection conn = null;
6702  1 PreparedStatement ps = null;
6703  1 ResultSet rs = null;
6704   
6705  1 String sqlQuery = SQLConstants.GET_EXTERNAL_WORKFLOW_FOR_SUBSCRIPTION_SQL;
6706  1 try {
6707  1 conn = APIMgtDBUtil.getConnection();
6708  1 ps = conn.prepareStatement(sqlQuery);
6709    // setting subscriptionId as string to prevent error when db finds string type IDs for
6710    // ApplicationRegistration workflows
6711  1 ps.setString(1, String.valueOf(subscriptionId));
6712  1 ps.setString(2, WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
6713  1 rs = ps.executeQuery();
6714   
6715    // returns only one row
6716  2 while (rs.next()) {
6717  1 workflowExtRef = rs.getString("WF_EXTERNAL_REFERENCE");
6718    }
6719    } catch (SQLException e) {
6720  0 handleException("Error occurred while getting workflow entry for " +
6721    "Subscription : " + subscriptionId, e);
6722    } finally {
6723  1 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
6724    }
6725  1 return workflowExtRef;
6726    }
6727   
6728    /**
6729    * Retries the WorkflowExternalReference for an user signup by DOMAIN/username.
6730    *
6731    * @param usernameWithDomain username of the signed up user inthe format of DOMAIN/username
6732    * @return External workflow reference for the signup workflow entry
6733    * @throws APIManagementException
6734    */
 
6735  29 toggle public String getExternalWorkflowReferenceForUserSignup(String usernameWithDomain) throws APIManagementException {
6736  29 String workflowExtRef = null;
6737  29 Connection conn = null;
6738  29 PreparedStatement ps = null;
6739  29 ResultSet rs = null;
6740   
6741  29 String sqlQuery = SQLConstants.GET_EXTERNAL_WORKFLOW_FOR_SIGNUP_SQL;
6742  29 try {
6743  29 conn = APIMgtDBUtil.getConnection();
6744  29 ps = conn.prepareStatement(sqlQuery);
6745  29 ps.setString(1, usernameWithDomain);
6746  29 ps.setString(2, WorkflowConstants.WF_TYPE_AM_USER_SIGNUP);
6747  29 rs = ps.executeQuery();
6748   
6749    // returns only one row
6750  29 while (rs.next()) {
6751  0 workflowExtRef = rs.getString("WF_EXTERNAL_REFERENCE");
6752    }
6753    } catch (SQLException e) {
6754  0 handleException("Error occurred while getting workflow entry for " +
6755    "User signup : " + usernameWithDomain, e);
6756    } finally {
6757  29 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
6758    }
6759  29 return workflowExtRef;
6760    }
6761   
6762    /**
6763    * Retrieves IDs of pending subscriptions for a given application
6764    *
6765    * @param applicationId application id of the application
6766    * @return Set containing subscription id list
6767    * @throws APIManagementException
6768    */
 
6769  130 toggle public Set<Integer> getPendingSubscriptionsByApplicationId(int applicationId) throws APIManagementException {
6770  130 Set<Integer> pendingSubscriptions = new HashSet<Integer>();
6771  130 Connection conn = null;
6772  130 PreparedStatement ps = null;
6773  130 ResultSet rs = null;
6774   
6775  130 String sqlQuery = SQLConstants.GET_PAGINATED_SUBSCRIPTIONS_BY_APPLICATION_SQL;
6776  130 try {
6777  130 conn = APIMgtDBUtil.getConnection();
6778  130 ps = conn.prepareStatement(sqlQuery);
6779  130 ps.setInt(1, applicationId);
6780  130 ps.setString(2, APIConstants.SubscriptionStatus.ON_HOLD);
6781  130 rs = ps.executeQuery();
6782   
6783  130 while (rs.next()) {
6784  0 pendingSubscriptions.add(rs.getInt("SUBSCRIPTION_ID"));
6785    }
6786    } catch (SQLException e) {
6787  0 handleException("Error occurred while getting subscription entries for " +
6788    "Application : " + applicationId, e);
6789    } finally {
6790  130 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
6791    }
6792  130 return pendingSubscriptions;
6793    }
6794   
6795    /**
6796    * Retrieves registration workflow reference for applicationId and key type
6797    *
6798    * @param applicationId id of the application with registration
6799    * @param keyType key type of the registration
6800    * @return workflow reference of the registration
6801    * @throws APIManagementException
6802    */
 
6803  0 toggle public String getRegistrationWFReference(int applicationId, String keyType) throws APIManagementException {
6804  0 Connection conn = null;
6805  0 PreparedStatement ps = null;
6806  0 ResultSet rs = null;
6807  0 String reference = null;
6808   
6809  0 String sqlQuery = SQLConstants.GET_REGISTRATION_WORKFLOW_SQL;
6810  0 try {
6811  0 conn = APIMgtDBUtil.getConnection();
6812  0 ps = conn.prepareStatement(sqlQuery);
6813  0 ps.setInt(1, applicationId);
6814  0 ps.setString(2, keyType);
6815  0 rs = ps.executeQuery();
6816   
6817    // returns only one row
6818  0 while (rs.next()) {
6819  0 reference = rs.getString("WF_REF");
6820    }
6821    } catch (SQLException e) {
6822  0 handleException("Error occurred while getting registration entry for " +
6823    "Application : " + applicationId, e);
6824    } finally {
6825  0 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
6826    }
6827  0 return reference;
6828    }
6829   
6830    /**
6831    * Retrives subscription status for APIIdentifier and applicationId
6832    *
6833    * @param identifier api identifier subscribed
6834    * @param applicationId application with subscription
6835    * @return subscription status
6836    * @throws APIManagementException
6837    */
 
6838  63 toggle public String getSubscriptionStatus(APIIdentifier identifier, int applicationId) throws APIManagementException {
6839  63 String status = null;
6840  63 Connection conn = null;
6841  63 PreparedStatement ps = null;
6842  63 ResultSet rs = null;
6843   
6844  63 String sqlQuery = SQLConstants.GET_SUBSCRIPTION_STATUS_SQL;
6845  63 try {
6846  63 conn = APIMgtDBUtil.getConnection();
6847  63 int apiId = getAPIID(identifier, conn);
6848  63 ps = conn.prepareStatement(sqlQuery);
6849  63 ps.setInt(1, apiId);
6850  63 ps.setInt(2, applicationId);
6851  63 rs = ps.executeQuery();
6852   
6853    // returns only one row
6854  125 while (rs.next()) {
6855  62 status = rs.getString("SUB_STATUS");
6856    }
6857    } catch (SQLException e) {
6858  0 handleException("Error occurred while getting subscription entry for " +
6859    "Application : " + applicationId + ", API: " + identifier, e);
6860    } finally {
6861  63 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
6862    }
6863  63 return status;
6864    }
6865   
6866    /**
6867    * Retrieve subscription create state for APIIdentifier and applicationID
6868    *
6869    * @param identifier - api identifier which is subscribed
6870    * @param applicationId - application used to subscribed
6871    * @param connection
6872    * @return subscription create status
6873    * @throws APIManagementException
6874    */
 
6875  2 toggle public String getSubscriptionCreaeteStatus(APIIdentifier identifier, int applicationId, Connection connection)
6876    throws APIManagementException {
6877  2 String status = null;
6878  2 PreparedStatement ps = null;
6879  2 ResultSet rs = null;
6880   
6881  2 String sqlQuery = SQLConstants.GET_SUBSCRIPTION_CREATION_STATUS_SQL;
6882  2 try {
6883  2 int apiId = getAPIID(identifier, connection);
6884  2 ps = connection.prepareStatement(sqlQuery);
6885  2 ps.setInt(1, apiId);
6886  2 ps.setInt(2, applicationId);
6887  2 rs = ps.executeQuery();
6888   
6889    // returns only one row
6890  2 while (rs.next()) {
6891  0 status = rs.getString("SUBS_CREATE_STATE");
6892    }
6893    } catch (SQLException e) {
6894  0 handleException("Error occurred while getting subscription entry for " +
6895    "Application : " + applicationId + ", API: " + identifier, e);
6896    } finally {
6897  2 APIMgtDBUtil.closeAllConnections(ps, null, rs);
6898    }
6899  2 return status;
6900    }
6901   
 
6902    private class SubscriptionInfo {
6903    private int subscriptionId;
6904    private String tierId;
6905    private int applicationId;
6906    private String accessToken;
6907    private String tokenType;
6908    }
6909   
6910    /**
6911    * Identify whether the loggedin user used his ordinal username or email
6912    *
6913    * @param userId
6914    * @return
6915    */
 
6916  0 toggle private boolean isUserLoggedInEmail(String userId) {
6917  0 return userId.contains("@");
6918    }
6919   
6920    /**
6921    * Identify whether the loggedin user used his Primary Login name or Secondary login name
6922    *
6923    * @param userId
6924    * @return
6925    */
 
6926  184 toggle private boolean isSecondaryLogin(String userId) {
6927  184 Map<String, Map<String, String>> loginConfiguration = ServiceReferenceHolder.getInstance()
6928    .getAPIManagerConfigurationService().getAPIManagerConfiguration().getLoginConfiguration();
6929  184 if (loginConfiguration.get(APIConstants.EMAIL_LOGIN) != null) {
6930  0 Map<String, String> emailConf = loginConfiguration.get(APIConstants.EMAIL_LOGIN);
6931  0 if ("true".equalsIgnoreCase(emailConf.get(APIConstants.PRIMARY_LOGIN))) {
6932  0 return !isUserLoggedInEmail(userId);
6933    }
6934  0 if ("false".equalsIgnoreCase(emailConf.get(APIConstants.PRIMARY_LOGIN))) {
6935  0 return isUserLoggedInEmail(userId);
6936    }
6937    }
6938  184 if (loginConfiguration.get(APIConstants.USERID_LOGIN) != null) {
6939  0 Map<String, String> userIdConf = loginConfiguration.get(APIConstants.USERID_LOGIN);
6940  0 if ("true".equalsIgnoreCase(userIdConf.get(APIConstants.PRIMARY_LOGIN))) {
6941  0 return isUserLoggedInEmail(userId);
6942    }
6943  0 if ("false".equalsIgnoreCase(userIdConf.get(APIConstants.PRIMARY_LOGIN))) {
6944  0 return !isUserLoggedInEmail(userId);
6945    }
6946    }
6947  184 return false;
6948    }
6949   
6950    /**
6951    * Get the primaryLogin name using secondary login name. Primary secondary
6952    * Configuration is provided in the identitiy.xml. In the userstore, it is
6953    * users responsibility TO MAINTAIN THE SECONDARY LOGIN NAME AS UNIQUE for
6954    * each and every users. If it is not unique, we will pick the very first
6955    * entry from the userlist.
6956    *
6957    * @param login
6958    * @return
6959    * @throws APIManagementException
6960    */
 
6961  0 toggle private String getPrimaryLoginFromSecondary(String login) throws APIManagementException {
6962  0 Map<String, Map<String, String>> loginConfiguration = ServiceReferenceHolder.getInstance()
6963    .getAPIManagerConfigurationService().getAPIManagerConfiguration().getLoginConfiguration();
6964  0 String claimURI, username = null;
6965  0 if (isUserLoggedInEmail(login)) {
6966  0 Map<String, String> emailConf = loginConfiguration.get(APIConstants.EMAIL_LOGIN);
6967  0 claimURI = emailConf.get(APIConstants.CLAIM_URI);
6968    } else {
6969  0 Map<String, String> userIdConf = loginConfiguration.get(APIConstants.USERID_LOGIN);
6970  0 claimURI = userIdConf.get(APIConstants.CLAIM_URI);
6971    }
6972   
6973  0 try {
6974  0 RemoteUserManagerClient rmUserClient = new RemoteUserManagerClient(login);
6975  0 String[] user = rmUserClient.getUserList(claimURI, login);
6976  0 if (user.length > 0) {
6977  0 username = user[0];
6978    }
6979    } catch (Exception e) {
6980   
6981  0 handleException("Error while retrieving the primaryLogin name using secondary loginName : " + login, e);
6982    }
6983  0 return username;
6984    }
6985   
6986    /**
6987    * identify the login username is primary or secondary
6988    *
6989    * @param userID
6990    * @return
6991    * @throws APIManagementException
6992    */
 
6993  184 toggle private String getLoginUserName(String userID) throws APIManagementException {
6994  184 String primaryLogin = userID;
6995  184 if (isSecondaryLogin(userID)) {
6996  0 primaryLogin = getPrimaryLoginFromSecondary(userID);
6997    }
6998  184 return primaryLogin;
6999    }
7000   
7001   
7002    /**
7003    * Store external APIStore details to which APIs successfully published
7004    *
7005    * @param apiId APIIdentifier
7006    * @param apiStoreSet APIStores set
7007    * @return added/failed
7008    * @throws APIManagementException
7009    */
 
7010  0 toggle public boolean addExternalAPIStoresDetails(APIIdentifier apiId, Set<APIStore> apiStoreSet)
7011    throws APIManagementException {
7012  0 Connection conn = null;
7013  0 PreparedStatement ps = null;
7014  0 boolean state = false;
7015  0 try {
7016  0 conn = APIMgtDBUtil.getConnection();
7017  0 conn.setAutoCommit(false);
7018   
7019    //This query to add external APIStores to database table
7020  0 String sqlQuery = SQLConstants.ADD_EXTERNAL_API_STORE_SQL;
7021   
7022    //Get API Id
7023  0 int apiIdentifier;
7024  0 apiIdentifier = getAPIID(apiId, conn);
7025  0 if (apiIdentifier == -1) {
7026  0 String msg = "Could not load API record for: " + apiId.getApiName();
7027  0 log.error(msg);
7028    }
7029  0 ps = conn.prepareStatement(sqlQuery);
7030  0 for (Object storeObject : apiStoreSet) {
7031  0 APIStore store = (APIStore) storeObject;
7032  0 ps.setInt(1, apiIdentifier);
7033  0 ps.setString(2, store.getName());
7034  0 ps.setString(3, store.getDisplayName());
7035  0 ps.setString(4, store.getEndpoint());
7036  0 ps.setString(5, store.getType());
7037  0 ps.addBatch();
7038    }
7039   
7040  0 ps.executeBatch();
7041  0 conn.commit();
7042  0 state = true;
7043    } catch (SQLException e) {
7044  0 if (conn != null) {
7045  0 try {
7046  0 conn.rollback();
7047    } catch (SQLException e1) {
7048  0 log.error("Failed to rollback storing external apistore details ", e1);
7049    }
7050    }
7051  0 log.error("Failed to store external apistore details", e);
7052  0 state = false;
7053    } catch (APIManagementException e) {
7054  0 log.error("Failed to store external apistore details", e);
7055  0 state = false;
7056    } finally {
7057  0 APIMgtDBUtil.closeAllConnections(ps, conn, null);
7058    }
7059  0 return state;
7060    }
7061   
7062    /**
7063    * Delete the records of external APIStore details.
7064    *
7065    * @param apiId APIIdentifier
7066    * @param apiStoreSet APIStores set
7067    * @return added/failed
7068    * @throws APIManagementException
7069    */
 
7070  0 toggle public boolean deleteExternalAPIStoresDetails(APIIdentifier apiId, Set<APIStore> apiStoreSet)
7071    throws APIManagementException {
7072  0 Connection conn = null;
7073  0 PreparedStatement ps = null;
7074  0 boolean state = false;
7075  0 try {
7076  0 conn = APIMgtDBUtil.getConnection();
7077  0 conn.setAutoCommit(false);
7078   
7079  0 String sqlQuery = SQLConstants.REMOVE_EXTERNAL_API_STORE_SQL;
7080   
7081    //Get API Id
7082  0 int apiIdentifier;
7083  0 apiIdentifier = getAPIID(apiId, conn);
7084  0 if (apiIdentifier == -1) {
7085  0 String msg = "Could not load API record for: " + apiId.getApiName();
7086  0 log.error(msg);
7087    }
7088  0 ps = conn.prepareStatement(sqlQuery);
7089  0 for (Object storeObject : apiStoreSet) {
7090  0 APIStore store = (APIStore) storeObject;
7091  0 ps.setInt(1, apiIdentifier);
7092  0 ps.setString(2, store.getName());
7093  0 ps.setString(3, store.getType());
7094  0 ps.addBatch();
7095    }
7096  0 ps.executeBatch();
7097   
7098  0 conn.commit();
7099  0 state = true;
7100    } catch (SQLException e) {
7101  0 if (conn != null) {
7102  0 try {
7103  0 conn.rollback();
7104    } catch (SQLException e1) {
7105  0 log.error("Failed to rollback deleting external apistore details ", e1);
7106    }
7107    }
7108  0 log.error("Failed to delete external apistore details", e);
7109  0 state = false;
7110    } catch (APIManagementException e) {
7111  0 log.error("Failed to delete external apistore details", e);
7112  0 state = false;
7113    } finally {
7114  0 APIMgtDBUtil.closeAllConnections(ps, conn, null);
7115    }
7116  0 return state;
7117    }
7118   
 
7119  0 toggle public void updateExternalAPIStoresDetails(APIIdentifier apiId, Set<APIStore> apiStoreSet)
7120    throws APIManagementException {
7121  0 Connection conn = null;
7122  0 try {
7123  0 conn = APIMgtDBUtil.getConnection();
7124  0 conn.setAutoCommit(false);
7125  0 updateExternalAPIStoresDetails(apiId, apiStoreSet, conn);
7126    } catch (SQLException e) {
7127  0 if (conn != null) {
7128  0 try {
7129  0 conn.rollback();
7130    } catch (SQLException e1) {
7131  0 log.error("Failed to rollback updating external apistore details ", e1);
7132    }
7133    }
7134  0 log.error("Failed to update external apistore details", e);
7135    } catch (APIManagementException e) {
7136  0 log.error("Failed to updating external apistore details", e);
7137    } finally {
7138  0 APIMgtDBUtil.closeAllConnections(null, conn, null);
7139    }
7140    }
7141   
7142    /**
7143    * Updateexternal APIStores details to which APIs published
7144    *
7145    * @param apiIdentifier API Identifier
7146    * @throws APIManagementException if failed to add Application
7147    */
 
7148  0 toggle public void updateExternalAPIStoresDetails(APIIdentifier apiIdentifier, Set<APIStore> apiStoreSet, Connection conn)
7149    throws APIManagementException, SQLException {
7150  0 PreparedStatement ps = null;
7151   
7152  0 try {
7153  0 conn.setAutoCommit(false);
7154    //This query to add external APIStores to database table
7155  0 String sqlQuery = SQLConstants.UPDATE_EXTERNAL_API_STORE_SQL;
7156   
7157  0 ps = conn.prepareStatement(sqlQuery);
7158    //Get API Id
7159  0 int apiId;
7160  0 apiId = getAPIID(apiIdentifier, conn);
7161  0 if (apiId == -1) {
7162  0 String msg = "Could not load API record for: " + apiIdentifier.getApiName();
7163  0 log.error(msg);
7164    }
7165   
7166  0 for (Object storeObject : apiStoreSet) {
7167  0 APIStore store = (APIStore) storeObject;
7168  0 ps.setString(1, store.getEndpoint());
7169  0 ps.setString(2, store.getType());
7170  0 ps.setInt(3, apiId);
7171  0 ps.setString(4, store.getName());
7172  0 ps.addBatch();
7173    }
7174   
7175  0 ps.executeBatch();
7176  0 ps.clearBatch();
7177   
7178  0 conn.commit();
7179    } catch (SQLException e) {
7180  0 log.error("Error while updating External APIStore details to the database for API : ", e);
7181    } finally {
7182  0 APIMgtDBUtil.closeAllConnections(ps, null, null);
7183    }
7184    }
7185   
7186    /**
7187    * Return external APIStore details on successfully APIs published
7188    *
7189    * @param apiId APIIdentifier
7190    * @return Set of APIStore
7191    * @throws APIManagementException
7192    */
 
7193  0 toggle public Set<APIStore> getExternalAPIStoresDetails(APIIdentifier apiId) throws APIManagementException {
7194  0 Connection conn = null;
7195  0 Set<APIStore> storesSet = new HashSet<APIStore>();
7196  0 try {
7197  0 conn = APIMgtDBUtil.getConnection();
7198  0 conn.setAutoCommit(false);
7199   
7200  0 storesSet = getExternalAPIStoresDetails(apiId, conn);
7201   
7202  0 conn.commit();
7203    } catch (SQLException e) {
7204  0 if (conn != null) {
7205  0 try {
7206  0 conn.rollback();
7207    } catch (SQLException e1) {
7208  0 log.error("Failed to rollback getting external apistore details ", e1);
7209    }
7210    }
7211  0 log.error("Failed to get external apistore details", e);
7212    } catch (APIManagementException e) {
7213  0 log.error("Failed to get external apistore details", e);
7214    } finally {
7215  0 APIMgtDBUtil.closeAllConnections(null, conn, null);
7216    }
7217  0 return storesSet;
7218    }
7219   
7220    /**
7221    * Get external APIStores details which are stored in database
7222    *
7223    * @param apiIdentifier API Identifier
7224    * @throws APIManagementException if failed to get external APIStores
7225    */
 
7226  0 toggle public Set<APIStore> getExternalAPIStoresDetails(APIIdentifier apiIdentifier, Connection conn)
7227    throws APIManagementException, SQLException {
7228  0 PreparedStatement ps = null;
7229  0 ResultSet rs = null;
7230  0 Set<APIStore> storesSet = new HashSet<APIStore>();
7231  0 try {
7232  0 conn = APIMgtDBUtil.getConnection();
7233    //This query to add external APIStores to database table
7234  0 String sqlQuery = SQLConstants.GET_EXTERNAL_API_STORE_DETAILS_SQL;
7235   
7236  0 ps = conn.prepareStatement(sqlQuery);
7237  0 int apiId;
7238  0 apiId = getAPIID(apiIdentifier, conn);
7239  0 if (apiId == -1) {
7240  0 String msg = "Could not load API record for: " + apiIdentifier.getApiName();
7241  0 log.error(msg);
7242  0 throw new APIManagementException(msg);
7243    }
7244  0 ps.setInt(1, apiId);
7245  0 rs = ps.executeQuery();
7246  0 while (rs.next()) {
7247  0 APIStore store = new APIStore();
7248  0 store.setName(rs.getString("STORE_ID"));
7249  0 store.setDisplayName(rs.getString("STORE_DISPLAY_NAME"));
7250  0 store.setEndpoint(rs.getString("STORE_ENDPOINT"));
7251  0 store.setType(rs.getString("STORE_TYPE"));
7252  0 store.setPublished(true);
7253  0 storesSet.add(store);
7254    }
7255    } catch (SQLException e) {
7256  0 handleException("Error while getting External APIStore details from the database for the API : " +
7257    apiIdentifier.getApiName() + '-' + apiIdentifier.getVersion(), e);
7258    } finally {
7259  0 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
7260    }
7261  0 return storesSet;
7262    }
7263   
 
7264  111 toggle public void addScopes(Set<?> objects, APIIdentifier apiIdentifier, int apiID, int tenantID)
7265    throws APIManagementException {
7266  111 Connection conn = null;
7267  111 PreparedStatement ps = null, ps2 = null, ps3 = null;
7268  111 ResultSet rs = null;
7269   
7270  111 String scopeEntry = SQLConstants.ADD_SCOPE_ENTRY_SQL;
7271  111 String scopeRoleEntry = SQLConstants.ADD_SCOPE_ROLE_SQL;
7272  111 String scopeLink = SQLConstants.ADD_SCOPE_LINK_SQL;
7273  111 Boolean scopeSharingEnabled = false;
7274  111 if (!StringUtils.isEmpty(System.getProperty(APIConstants.ENABLE_API_SCOPES_SHARING))) {
7275  0 scopeSharingEnabled = Boolean.parseBoolean(System.getProperty(APIConstants.ENABLE_API_SCOPES_SHARING));
7276    }
7277  111 try {
7278  111 conn = APIMgtDBUtil.getConnection();
7279  111 conn.setAutoCommit(false);
7280   
7281  111 String scopeId = "SCOPE_ID";
7282  111 if (conn.getMetaData().getDriverName().contains("PostgreSQL")) {
7283  0 scopeId = "scope_id";
7284    }
7285   
7286  111 if (objects != null) {
7287  111 for (Object object : objects) {
7288  134 ps = conn.prepareStatement(scopeEntry, new String[]{scopeId});
7289  134 ps2 = conn.prepareStatement(scopeLink);
7290  134 ps3 = conn.prepareStatement(scopeRoleEntry);
7291  134 if (object instanceof URITemplate) {
7292  126 URITemplate uriTemplate = (URITemplate) object;
7293   
7294  126 if (uriTemplate.getScope() == null) {
7295  108 continue;
7296    }
7297   
7298  18 if (!scopeSharingEnabled && isScopeKeyAssigned(apiIdentifier, uriTemplate.getScope().getKey(), tenantID)) {
7299  0 throw new APIManagementException("Scope '" + uriTemplate.getScope().getKey() + "' " +
7300    "is already used by another API.");
7301    }
7302   
7303  18 ps.setString(1, uriTemplate.getScope().getKey());
7304  18 ps.setString(2, uriTemplate.getScope().getName());
7305  18 ps.setString(3, uriTemplate.getScope().getDescription());
7306  18 ps.setInt(4, tenantID);
7307  18 ps.execute();
7308  18 rs = ps.getGeneratedKeys();
7309  18 if (rs.next()) {
7310  18 uriTemplate.getScope().setId(rs.getInt(1));
7311    }
7312   
7313  18 String roles = uriTemplate.getScope().getRoles();
7314    //Adding scope bindings
7315  18 List<String> roleList = Lists.newArrayList(Splitter.on(",").trimResults().split(roles));
7316  18 for (String role : roleList) {
7317  21 if (StringUtils.isNotBlank(role)) {
7318  21 ps3.setInt(1, uriTemplate.getScope().getId());
7319  21 ps3.setString(2, role);
7320  21 ps3.addBatch();
7321    }
7322    }
7323  18 ps3.executeBatch();
7324   
7325  18 ps2.setInt(1, apiID);
7326  18 ps2.setInt(2, uriTemplate.getScope().getId());
7327  18 ps2.execute();
7328  18 conn.commit();
7329  8 } else if (object instanceof Scope) {
7330  8 Scope scope = (Scope) object;
7331  8 if (!scopeSharingEnabled && isScopeKeyAssigned(apiIdentifier, scope.getKey(), tenantID)) {
7332  0 throw new APIManagementException("Scope '" + scope.getKey() + "' is already used " +
7333    "by another API.");
7334    }
7335  8 ps.setString(1, scope.getKey());
7336  8 ps.setString(2, scope.getName());
7337  8 ps.setString(3, scope.getDescription());
7338  8 ps.setInt(4, tenantID);
7339   
7340  8 ps.execute();
7341  8 rs = ps.getGeneratedKeys();
7342  8 if (rs.next()) {
7343  8 scope.setId(rs.getInt(1));
7344    }
7345   
7346  8 String roles = scope.getRoles();
7347    //Adding scope bindings
7348  8 List<String> roleList = Lists.newArrayList(Splitter.on(",").trimResults().split(roles));
7349  8 for (String role : roleList) {
7350  8 if (StringUtils.isNotBlank(role)) {
7351  8 ps3.setInt(1, scope.getId());
7352  8 ps3.setString(2, role);
7353  8 ps3.addBatch();
7354    }
7355    }
7356  8 ps3.executeBatch();
7357  8 ps2.setInt(1, apiID);
7358  8 ps2.setInt(2, scope.getId());
7359  8 ps2.execute();
7360  8 conn.commit();
7361    }
7362    }
7363    }
7364    } catch (SQLException e) {
7365  0 try {
7366  0 if (conn != null) {
7367  0 conn.rollback();
7368    }
7369    } catch (SQLException e1) {
7370  0 handleException("Error occurred while Rolling back changes done on Scopes Creation", e1);
7371    }
7372  0 handleException("Error occurred while creating scopes ", e);
7373    } finally {
7374  111 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
7375  111 APIMgtDBUtil.closeAllConnections(ps2, null, null);
7376    }
7377    }
7378   
7379    /**
7380    * Check a given scope key already exist for a tenant
7381    *
7382    * @param scopeKey Scope Key
7383    * @param tenantId Tenant ID
7384    * @return true if scope already exists
7385    * @throws APIManagementException if an error occurs while executing db query
7386    */
 
7387  0 toggle private boolean isScopeExists(String scopeKey, int tenantId) throws APIManagementException {
7388  0 Connection conn = null;
7389  0 ResultSet resultSet = null;
7390  0 PreparedStatement ps = null;
7391  0 try {
7392  0 conn = APIMgtDBUtil.getConnection();
7393   
7394  0 String sqlQuery = SQLConstants.GET_SCOPES_SQL;
7395  0 ps = conn.prepareStatement(sqlQuery);
7396  0 ps.setString(1, scopeKey);
7397  0 ps.setInt(2, tenantId);
7398  0 resultSet = ps.executeQuery();
7399  0 if (resultSet.next()) {
7400  0 if (log.isDebugEnabled()) {
7401  0 log.debug("Scope key " + scopeKey + " for tenant " + tenantId + " exists.");
7402    }
7403  0 return true;
7404    }
7405    } catch (SQLException e) {
7406  0 handleException("Failed to check scope exists for scope " + scopeKey, e);
7407    } finally {
7408  0 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
7409    }
7410  0 return false;
7411    }
7412   
 
7413  3158 toggle public Set<Scope> getAPIScopes(APIIdentifier identifier) throws APIManagementException {
7414  3158 Connection conn = null;
7415  3158 ResultSet resultSet = null;
7416  3158 PreparedStatement ps = null;
7417  3158 HashMap<Integer, Scope> scopeHashMap = new HashMap<>();
7418  3158 int apiId;
7419  3158 try {
7420  3158 conn = APIMgtDBUtil.getConnection();
7421  3158 apiId = getAPIID(identifier, conn);
7422   
7423  3158 String sqlQuery = SQLConstants.GET_API_SCOPES_SQL;
7424  3158 if (conn.getMetaData().getDriverName().contains("Oracle")) {
7425  0 sqlQuery = SQLConstants.GET_API_SCOPES_ORACLE_SQL;
7426    }
7427   
7428  3158 ps = conn.prepareStatement(sqlQuery);
7429  3158 ps.setInt(1, apiId);
7430  3158 resultSet = ps.executeQuery();
7431  3308 while (resultSet.next()) {
7432  150 Scope scope;
7433  150 int scopeId = resultSet.getInt(1);
7434  150 if (scopeHashMap.containsKey(scopeId)) {
7435    // scope already exists append roles.
7436  14 scope = scopeHashMap.get(scopeId);
7437  14 scope.setRoles(scope.getRoles().concat("," + resultSet.getString(5)).trim());
7438    } else {
7439  136 scope = new Scope();
7440  136 scope.setId(scopeId);
7441  136 scope.setKey(resultSet.getString(2));
7442  136 scope.setName(resultSet.getString(3));
7443  136 scope.setDescription(resultSet.getString(4));
7444  136 scope.setRoles(resultSet.getString(5).trim());
7445    }
7446  150 scopeHashMap.put(scopeId, scope);
7447    }
7448   
7449    } catch (SQLException e) {
7450  0 handleException("Failed to retrieve api scopes ", e);
7451    } finally {
7452  3158 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
7453    }
7454  3158 return populateScopeSet(scopeHashMap);
7455    }
7456   
7457    /**
7458    * Generate Set<Scope> from HashMap
7459    *
7460    * @return Set of Scopes populated with roles.
7461    */
 
7462  3216 toggle private Set<Scope> populateScopeSet(HashMap<?, Scope> scopeHashMap) {
7463  3216 Set<Scope> scopes = new LinkedHashSet<Scope>();
7464  3216 for (Scope scope : scopeHashMap.values()) {
7465  144 scopes.add(scope);
7466    }
7467  3216 return scopes;
7468    }
7469   
7470    /**
7471    * Returns all the scopes assigned for given apis
7472    *
7473    * @param apiIdsString list of api ids separated by commas
7474    * @return Map<String, Set<Scope>> set of scopes for each apiId
7475    * @throws APIManagementException
7476    */
 
7477  36 toggle public Map<String, Set<Scope>> getScopesForAPIS(String apiIdsString) throws APIManagementException {
7478   
7479  36 ResultSet resultSet = null;
7480  36 PreparedStatement ps = null;
7481  36 Map<String, Set<Scope>> apiScopeSet = new HashMap<String, Set<Scope>>();
7482   
7483  36 try (Connection conn = APIMgtDBUtil.getConnection()) {
7484   
7485  36 String sqlQuery = SQLConstants.GET_SCOPES_FOR_API_LIST;
7486   
7487  36 if (conn.getMetaData().getDriverName().contains("Oracle")) {
7488  0 sqlQuery = SQLConstants.GET_SCOPES_FOR_API_LIST_ORACLE;
7489    }
7490   
7491    // apids are retrieved from the db so no need to protect for sql injection
7492  36 sqlQuery = sqlQuery.replace("$paramList", apiIdsString);
7493  36 ps = conn.prepareStatement(sqlQuery);
7494  36 resultSet = ps.executeQuery();
7495  36 while (resultSet.next()) {
7496   
7497  0 String apiId = resultSet.getString(1);
7498  0 Scope scope = new Scope();
7499  0 scope.setId(resultSet.getInt(2));
7500  0 scope.setName(resultSet.getString(3));
7501  0 scope.setDescription(resultSet.getString(4));
7502   
7503  0 Set<Scope> scopeList = apiScopeSet.get(apiId);
7504   
7505  0 if (scopeList == null) {
7506  0 scopeList = new LinkedHashSet<Scope>();
7507  0 scopeList.add(scope);
7508  0 apiScopeSet.put(apiId, scopeList);
7509    } else {
7510  0 scopeList.add(scope);
7511  0 apiScopeSet.put(apiId, scopeList);
7512    }
7513    }
7514    } catch (SQLException e) {
7515  0 handleException("Failed to retrieve api scopes ", e);
7516    }
7517  36 return apiScopeSet;
7518    }
7519   
7520   
 
7521  54 toggle public Set<Scope> getScopesBySubscribedAPIs(List<APIIdentifier> identifiers) throws APIManagementException {
7522  54 Connection conn = null;
7523  54 ResultSet resultSet = null;
7524  54 PreparedStatement ps = null;
7525  54 List<Integer> apiIds = new ArrayList<Integer>();
7526  54 HashMap<String, Scope> scopeHashMap = new HashMap<>();
7527  54 try {
7528  54 conn = APIMgtDBUtil.getConnection();
7529  54 for (APIIdentifier identifier : identifiers) {
7530  58 apiIds.add(getAPIID(identifier, conn));
7531    }
7532   
7533  54 String commaSeparatedIds = StringUtils.join(apiIds.iterator(), ',');
7534  54 String sqlQuery = SQLConstants.GET_SCOPE_BY_SUBSCRIBED_API_PREFIX + commaSeparatedIds + SQLConstants
7535    .GET_SCOPE_BY_SUBSCRIBED_ID_SUFFIX;
7536   
7537  54 if (conn.getMetaData().getDriverName().contains("Oracle")) {
7538  0 sqlQuery = SQLConstants.GET_SCOPE_BY_SUBSCRIBED_ID_ORACLE_SQL + commaSeparatedIds +
7539    SQLConstants.GET_SCOPE_BY_SUBSCRIBED_ID_SUFFIX;
7540    }
7541   
7542  54 ps = conn.prepareStatement(sqlQuery);
7543  54 resultSet = ps.executeQuery();
7544  58 while (resultSet.next()) {
7545  4 Scope scope;
7546  4 String scopeKey = resultSet.getString(1);
7547  4 if (scopeHashMap.containsKey(scopeKey)) {
7548    // scope already exists append roles.
7549  0 scope = scopeHashMap.get(scopeKey);
7550  0 String roles = scope.getRoles();
7551  0 if (StringUtils.isNotEmpty(roles)) {
7552  0 scope.setRoles(scope.getRoles().concat("," + resultSet.getString(4)).trim());
7553    }
7554    } else {
7555  4 scope = new Scope();
7556  4 scope.setKey(scopeKey);
7557  4 scope.setName(resultSet.getString(2));
7558  4 scope.setDescription(resultSet.getString(3));
7559  4 String roles = resultSet.getString(4);
7560  4 if (StringUtils.isNotEmpty(roles)) {
7561  4 scope.setRoles(resultSet.getString(4).trim());
7562    }
7563    }
7564  4 scopeHashMap.put(scopeKey, scope);
7565    }
7566    } catch (SQLException e) {
7567  0 handleException("Failed to retrieve api scopes ", e);
7568    } finally {
7569  54 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
7570    }
7571  54 return populateScopeSet(scopeHashMap);
7572    }
7573   
 
7574  0 toggle public Set<Scope> getAPIScopesByScopeKey(String scopeKey, int tenantId) throws APIManagementException {
7575  0 Connection conn = null;
7576  0 ResultSet resultSet = null;
7577  0 PreparedStatement ps = null;
7578  0 HashMap<Integer, Scope> scopeHashMap = new HashMap<>();
7579  0 try {
7580  0 String sqlQuery = SQLConstants.GET_SCOPES_BY_SCOPE_KEY_SQL;
7581  0 conn = APIMgtDBUtil.getConnection();
7582   
7583  0 ps = conn.prepareStatement(sqlQuery);
7584  0 ps.setString(1, scopeKey);
7585  0 ps.setInt(2, tenantId);
7586  0 resultSet = ps.executeQuery();
7587  0 while (resultSet.next()) {
7588  0 Scope scope;
7589  0 int scopeId = resultSet.getInt(1);
7590  0 if (scopeHashMap.containsKey(scopeId)) {
7591    // scope already exists append roles.
7592  0 scope = scopeHashMap.get(scopeId);
7593  0 scope.setRoles(scope.getRoles().concat("," + resultSet.getString(5)).trim());
7594    } else {
7595  0 scope = new Scope();
7596  0 scope.setId(scopeId);
7597  0 scope.setKey(resultSet.getString(2));
7598  0 scope.setName(resultSet.getString(3));
7599  0 scope.setDescription(resultSet.getString(4));
7600  0 scope.setRoles(resultSet.getString(5).trim());
7601    }
7602  0 scopeHashMap.put(scopeId, scope);
7603    }
7604    } catch (SQLException e) {
7605  0 handleException("Failed to retrieve api scopes ", e);
7606    } finally {
7607  0 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
7608    }
7609  0 return populateScopeSet(scopeHashMap);
7610    }
7611   
 
7612  4 toggle public Set<Scope> getScopesByScopeKeys(String scopeKeys, int tenantId) throws APIManagementException {
7613  4 Connection conn = null;
7614  4 ResultSet resultSet = null;
7615  4 PreparedStatement ps = null;
7616  4 List<String> inputScopeList = Arrays.asList(scopeKeys.split(" "));
7617  4 StringBuilder placeHolderBuilder = new StringBuilder();
7618  4 HashMap<Integer, Scope> scopeHashMap = new HashMap<>();
7619  8 for (int i = 0; i < inputScopeList.size(); i++) {
7620  4 placeHolderBuilder.append("?, ");
7621    }
7622   
7623  4 String placeHolderStr = placeHolderBuilder.deleteCharAt(placeHolderBuilder.length() - 2).toString();
7624  4 try {
7625  4 conn = APIMgtDBUtil.getConnection();
7626  4 String sqlQuery = SQLConstants.GET_SCOPES_BY_SCOPE_KEYS_PREFIX + placeHolderStr + SQLConstants
7627    .GET_SCOPES_BY_SCOPE_KEYS_SUFFIX;
7628  4 if (conn.getMetaData().getDriverName().contains("Oracle")) {
7629  0 sqlQuery = SQLConstants.GET_SCOPES_BY_SCOPE_KEYS_PREFIX_ORACLE + placeHolderStr
7630    + SQLConstants.GET_SCOPES_BY_SCOPE_KEYS_SUFFIX;
7631    }
7632  4 ps = conn.prepareStatement(sqlQuery);
7633   
7634  8 for (int i = 0; i < inputScopeList.size(); i++) {
7635  4 ps.setString(i + 1, inputScopeList.get(i));
7636    }
7637   
7638  4 ps.setInt(inputScopeList.size() + 1, tenantId);
7639   
7640  4 resultSet = ps.executeQuery();
7641  8 while (resultSet.next()) {
7642  4 Scope scope;
7643  4 int scopeId = resultSet.getInt(1);
7644  4 if (scopeHashMap.containsKey(scopeId)) {
7645    // scope already exists append roles.
7646  0 scope = scopeHashMap.get(scopeId);
7647  0 scope.setRoles(scope.getRoles().concat("," + resultSet.getString(6)).trim());
7648    } else {
7649  4 scope = new Scope();
7650  4 scope.setId(scopeId);
7651  4 scope.setKey(resultSet.getString(2));
7652  4 scope.setName(resultSet.getString(3));
7653  4 scope.setDescription(resultSet.getString(4));
7654  4 scope.setRoles(resultSet.getString(6).trim());
7655    }
7656  4 scopeHashMap.put(scopeId, scope);
7657    }
7658    } catch (SQLException e) {
7659  0 handleException("Failed to retrieve api scopes ", e);
7660    } finally {
7661  4 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
7662    }
7663  4 return populateScopeSet(scopeHashMap);
7664    }
7665   
7666    /**
7667    * update URI templates define for an API
7668    *
7669    * @param api
7670    * @throws APIManagementException
7671    */
 
7672  66 toggle public void updateScopes(API api, int tenantId) throws APIManagementException {
7673   
7674  66 Connection connection = null;
7675  66 PreparedStatement prepStmt = null;
7676  66 int apiId = -1;
7677   
7678  66 String deleteResourceScopes = SQLConstants.REMOVE_RESOURCE_SCOPE_SQL;
7679  66 String deleteScopes = SQLConstants.REMOVE_SCOPE_SQL;
7680   
7681  66 try {
7682  66 connection = APIMgtDBUtil.getConnection();
7683  66 connection.setAutoCommit(false);
7684   
7685  66 apiId = getAPIID(api.getId(), connection);
7686  66 if (apiId == -1) {
7687    //application addition has failed
7688  0 return;
7689    }
7690   
7691  66 prepStmt = connection.prepareStatement(deleteResourceScopes);
7692  66 prepStmt.setInt(1, apiId);
7693  66 prepStmt.execute();
7694   
7695  66 prepStmt = connection.prepareStatement(deleteScopes);
7696  66 prepStmt.setInt(1, apiId);
7697  66 prepStmt.execute();
7698   
7699  66 connection.commit();
7700    } catch (SQLException e) {
7701  0 handleException("Error while deleting Scopes for API : " + api.getId(), e);
7702    } finally {
7703  66 APIMgtDBUtil.closeAllConnections(prepStmt, connection, null);
7704    }
7705  66 addScopes(api.getUriTemplates(), api.getId(), apiId, tenantId);
7706    }
7707   
 
7708  2899 toggle public HashMap<String, String> getResourceToScopeMapping(APIIdentifier identifier) throws APIManagementException {
7709  2899 Connection conn = null;
7710  2899 ResultSet resultSet = null;
7711  2899 PreparedStatement ps = null;
7712  2899 HashMap<String, String> map = new HashMap<String, String>();
7713  2899 int apiId;
7714  2899 try {
7715  2899 String sqlQuery = SQLConstants.GET_RESOURCE_TO_SCOPE_MAPPING_SQL;
7716  2899 apiId = getAPIID(identifier, conn);
7717   
7718  2899 conn = APIMgtDBUtil.getConnection();
7719  2899 ps = conn.prepareStatement(sqlQuery);
7720  2899 ps.setInt(1, apiId);
7721  2899 resultSet = ps.executeQuery();
7722  3015 while (resultSet.next()) {
7723  116 map.put(resultSet.getString(1), resultSet.getString(2));
7724    }
7725    } catch (SQLException e) {
7726  0 handleException("Failed to retrieve api scopes ", e);
7727    } finally {
7728  2899 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
7729    }
7730  2899 return map;
7731    }
7732   
 
7733  215 toggle public Map<String, String> getScopeRolesOfApplication(String consumerKey) throws APIManagementException {
7734  215 Connection conn = null;
7735  215 ResultSet resultSet = null;
7736  215 PreparedStatement ps = null;
7737   
7738  215 try {
7739  215 conn = APIMgtDBUtil.getConnection();
7740   
7741  215 String sqlQuery = SQLConstants.GET_SCOPE_ROLES_OF_APPLICATION_SQL;
7742   
7743  215 ps = conn.prepareStatement(sqlQuery);
7744  215 ps.setString(1, consumerKey);
7745  215 resultSet = ps.executeQuery();
7746  215 Map<String, String> scopes = new HashMap<String, String>();
7747  243 while (resultSet.next()) {
7748  28 if (scopes.containsKey(resultSet.getString(1))) {
7749    // Role for the scope exists. Append the new role.
7750  8 String roles = scopes.get(resultSet.getString(1));
7751  8 roles += "," + resultSet.getString(2);
7752  8 scopes.put(resultSet.getString(1), roles);
7753    } else {
7754  20 scopes.put(resultSet.getString(1), resultSet.getString(2));
7755    }
7756    }
7757  215 return scopes;
7758    } catch (SQLException e) {
7759  0 handleException("Failed to retrieve scopes of application" + consumerKey, e);
7760    } finally {
7761  215 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
7762    }
7763  0 return null;
7764    }
7765   
7766    /**
7767    * Remove scope entries from DB, when delete APIs
7768    *
7769    * @param apiIdentifier The {@link APIIdentifier} of the API
7770    */
 
7771  259 toggle private void removeAPIScope(APIIdentifier apiIdentifier) throws APIManagementException {
7772  259 Set<Scope> scopes = getAPIScopes(apiIdentifier);
7773   
7774  259 Connection connection = null;
7775  259 PreparedStatement prepStmt = null;
7776  259 PreparedStatement deleteOauth2ResourceScopePrepStmt = null;
7777  259 PreparedStatement deleteOauth2ScopePrepStmt = null;
7778  259 int scopeId;
7779  259 int apiId = -1;
7780   
7781  259 String deleteAPIScopeQuery = SQLConstants.REMOVE_FROM_API_SCOPES_SQL;
7782  259 String deleteOauth2ScopeQuery = SQLConstants.REMOVE_FROM_OAUTH_SCOPE_SQL;
7783  259 String deleteOauth2ResourceScopeQuery = SQLConstants.REMOVE_FROM_OAUTH_RESOURCE_SQL;
7784   
7785  259 try {
7786  259 connection = APIMgtDBUtil.getConnection();
7787  259 connection.setAutoCommit(false);
7788   
7789  259 prepStmt = connection.prepareStatement(deleteAPIScopeQuery);
7790  259 prepStmt.setInt(1, apiId);
7791  259 prepStmt.execute();
7792   
7793  259 if (!scopes.isEmpty()) {
7794  12 deleteOauth2ResourceScopePrepStmt = connection.prepareStatement(deleteOauth2ResourceScopeQuery);
7795  12 deleteOauth2ScopePrepStmt = connection.prepareStatement(deleteOauth2ScopeQuery);
7796  12 for (Scope scope : scopes) {
7797  20 scopeId = scope.getId();
7798   
7799  20 deleteOauth2ResourceScopePrepStmt.setInt(1, scopeId);
7800  20 deleteOauth2ResourceScopePrepStmt.addBatch();
7801   
7802  20 deleteOauth2ScopePrepStmt.setInt(1, scopeId);
7803  20 deleteOauth2ScopePrepStmt.addBatch();
7804    }
7805  12 deleteOauth2ResourceScopePrepStmt.executeBatch();
7806  12 deleteOauth2ScopePrepStmt.executeBatch();
7807    }
7808   
7809  259 connection.commit();
7810    } catch (SQLException e) {
7811  0 handleException("Error while removing the scopes for the API: " +
7812    apiIdentifier.getApiName() + " from the database", e);
7813    } finally {
7814  259 APIMgtDBUtil.closeAllConnections(deleteOauth2ResourceScopePrepStmt, null, null);
7815  259 APIMgtDBUtil.closeAllConnections(deleteOauth2ScopePrepStmt, null, null);
7816  259 APIMgtDBUtil.closeAllConnections(prepStmt, connection, null);
7817    }
7818    }
7819   
7820    /**
7821    * Delete a user subscription based on API_ID, APP_ID, TIER_ID
7822    *
7823    * @param apiId - subscriber API ID
7824    * @param appId - application ID used to subscribe
7825    * @throws java.sql.SQLException - Letting the caller to handle the roll back
7826    */
 
7827  0 toggle private void deleteSubscriptionByApiIDAndAppID(int apiId, int appId, Connection conn) throws SQLException {
7828  0 String deleteQuery = SQLConstants.REMOVE_SUBSCRIPTION_BY_APPLICATION_ID_SQL;
7829  0 PreparedStatement ps = null;
7830  0 try {
7831  0 ps = conn.prepareStatement(deleteQuery);
7832  0 ps.setInt(1, apiId);
7833  0 ps.setInt(2, appId);
7834   
7835  0 ps.executeUpdate();
7836    } finally {
7837  0 APIMgtDBUtil.closeAllConnections(ps, null, null);
7838    }
7839    }
7840   
7841    /**
7842    * Check the given api name is already available in the api table under given tenant domain
7843    *
7844    * @param apiName candidate api name
7845    * @param tenantDomain tenant domain name
7846    * @return true if the name is already available
7847    * @throws APIManagementException
7848    */
 
7849  1 toggle public boolean isApiNameExist(String apiName, String tenantDomain) throws APIManagementException {
7850  1 Connection connection = null;
7851  1 PreparedStatement prepStmt = null;
7852  1 ResultSet resultSet = null;
7853  1 String contextParam = "/t/";
7854   
7855  1 String query = SQLConstants.GET_API_NAME_NOT_MATCHING_CONTEXT_SQL;
7856  1 if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
7857  0 query = SQLConstants.GET_API_NAME_MATCHING_CONTEXT_SQL;
7858  0 contextParam += tenantDomain + '/';
7859    }
7860   
7861  1 try {
7862  1 connection = APIMgtDBUtil.getConnection();
7863   
7864  1 prepStmt = connection.prepareStatement(query);
7865  1 prepStmt.setString(1, apiName);
7866  1 prepStmt.setString(2, contextParam + '%');
7867  1 resultSet = prepStmt.executeQuery();
7868   
7869  1 int apiCount = 0;
7870  1 if (resultSet != null) {
7871  2 while (resultSet.next()) {
7872  1 apiCount = resultSet.getInt("API_COUNT");
7873    }
7874    }
7875  1 if (apiCount > 0) {
7876  1 return true;
7877    }
7878    } catch (SQLException e) {
7879  0 handleException("Failed to check api Name availability : " + apiName, e);
7880    } finally {
7881  1 APIMgtDBUtil.closeAllConnections(prepStmt, connection, resultSet);
7882    }
7883  0 return false;
7884    }
7885   
7886    /**
7887    * Check whether another API with a different letter case of the given api name is already available in the api
7888    * table under the given tenant domain
7889    *
7890    * @param apiName candidate api name
7891    * @param tenantDomain tenant domain name
7892    * @return true if a different letter case name is already available
7893    * @throws APIManagementException If failed to check different letter case api name availability
7894    */
 
7895  251 toggle public boolean isApiNameWithDifferentCaseExist(String apiName, String tenantDomain) throws APIManagementException {
7896  251 Connection connection = null;
7897  251 PreparedStatement prepStmt = null;
7898  251 ResultSet resultSet = null;
7899  251 String contextParam = "/t/";
7900   
7901  251 String query = SQLConstants.GET_API_NAME_DIFF_CASE_NOT_MATCHING_CONTEXT_SQL;
7902  251 if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
7903  67 query = SQLConstants.GET_API_NAME_DIFF_CASE_MATCHING_CONTEXT_SQL;
7904  67 contextParam += tenantDomain + '/';
7905    }
7906   
7907  251 try {
7908  251 connection = APIMgtDBUtil.getConnection();
7909   
7910  251 prepStmt = connection.prepareStatement(query);
7911  251 prepStmt.setString(1, apiName);
7912  251 prepStmt.setString(2, contextParam + '%');
7913  251 prepStmt.setString(3, apiName);
7914  251 resultSet = prepStmt.executeQuery();
7915   
7916  251 int apiCount = 0;
7917  251 if (resultSet != null) {
7918  502 while (resultSet.next()) {
7919  251 apiCount = resultSet.getInt("API_COUNT");
7920    }
7921    }
7922  251 if (apiCount > 0) {
7923  2 return true;
7924    }
7925    } catch (SQLException e) {
7926  0 handleException("Failed to check different letter case api name availability : " + apiName, e);
7927    } finally {
7928  251 APIMgtDBUtil.closeAllConnections(prepStmt, connection, resultSet);
7929    }
7930  249 return false;
7931    }
7932   
 
7933  163 toggle public Set<String> getActiveTokensOfConsumerKey(String consumerKey) throws APIManagementException {
7934  163 Connection conn = null;
7935  163 ResultSet resultSet = null;
7936  163 PreparedStatement ps = null;
7937   
7938  163 Set<String> tokens = null;
7939  163 try {
7940  163 conn = APIMgtDBUtil.getConnection();
7941  163 String sqlQuery = SQLConstants.GET_ACTIVE_TOKEN_OF_CONSUMER_KEY_SQL;
7942   
7943  163 ps = conn.prepareStatement(sqlQuery);
7944  163 ps.setString(1, consumerKey);
7945  163 resultSet = ps.executeQuery();
7946  163 tokens = new HashSet<String>();
7947  349 while (resultSet.next()) {
7948  186 tokens.add(APIUtil.decryptToken(resultSet.getString("ACCESS_TOKEN")));
7949    }
7950    } catch (SQLException e) {
7951  0 handleException("Failed to get active access tokens for consumerKey " + consumerKey, e);
7952    } catch (CryptoException e) {
7953  0 handleException("Token decryption failed of an active access token of consumerKey " + consumerKey, e);
7954    } finally {
7955  163 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
7956    }
7957  163 return tokens;
7958    }
7959   
7960    /**
7961    * Check the given scope key is already available under given tenant
7962    *
7963    * @param scopeKey candidate scope key
7964    * @param tenantId tenant id
7965    * @return true if the scope key is already available
7966    * @throws APIManagementException
7967    */
 
7968  0 toggle public boolean isScopeKeyExist(String scopeKey, int tenantId) throws APIManagementException {
7969  0 Connection connection = null;
7970  0 PreparedStatement prepStmt = null;
7971  0 ResultSet resultSet = null;
7972   
7973  0 String query = SQLConstants.GET_SCOPE_KEY_SQL;
7974  0 try {
7975  0 connection = APIMgtDBUtil.getConnection();
7976   
7977  0 prepStmt = connection.prepareStatement(query);
7978  0 prepStmt.setString(1, scopeKey);
7979  0 prepStmt.setInt(2, tenantId);
7980  0 resultSet = prepStmt.executeQuery();
7981   
7982  0 int scopeCount = 0;
7983  0 if (resultSet != null) {
7984  0 while (resultSet.next()) {
7985  0 scopeCount = resultSet.getInt("SCOPE_COUNT");
7986    }
7987    }
7988  0 if (scopeCount > 0) {
7989  0 return true;
7990    }
7991    } catch (SQLException e) {
7992  0 handleException("Failed to check Scope Key availability : " + scopeKey, e);
7993    } finally {
7994  0 APIMgtDBUtil.closeAllConnections(prepStmt, connection, resultSet);
7995    }
7996  0 return false;
7997    }
7998   
7999    /**
8000    * Check whether the given scope key is already assigned to another API than given under given tenant
8001    *
8002    * @param identifier API Identifier
8003    * @param scopeKey candidate scope key
8004    * @param tenantId tenant id
8005    * @return true if the scope key is already available
8006    * @throws APIManagementException if failed to check the context availability
8007    */
 
8008  38 toggle public boolean isScopeKeyAssigned(APIIdentifier identifier, String scopeKey, int tenantId)
8009    throws APIManagementException {
8010  38 Connection connection = null;
8011  38 PreparedStatement prepStmt = null;
8012  38 PreparedStatement prepStmt2 = null;
8013  38 ResultSet resultSet = null;
8014  38 ResultSet resultSet2 = null;
8015   
8016  38 String apiScopeQuery = SQLConstants.GET_API_SCOPE_SQL;
8017  38 String getApiQuery = SQLConstants.GET_API_ID_SQL;
8018   
8019  38 try {
8020  38 connection = APIMgtDBUtil.getConnection();
8021   
8022  38 prepStmt = connection.prepareStatement(apiScopeQuery);
8023  38 prepStmt.setString(1, scopeKey);
8024  38 prepStmt.setInt(2, tenantId);
8025  38 resultSet = prepStmt.executeQuery();
8026   
8027  38 if (resultSet != null && resultSet.next()) {
8028  4 int apiID = resultSet.getInt("API_ID");
8029  4 String provider = resultSet.getString("API_PROVIDER");
8030  4 String apiName = resultSet.getString("API_NAME");
8031   
8032  4 prepStmt2 = connection.prepareStatement(getApiQuery);
8033  4 prepStmt2.setString(1, APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
8034  4 prepStmt2.setString(2, identifier.getApiName());
8035  4 prepStmt2.setString(3, identifier.getVersion());
8036  4 resultSet2 = prepStmt2.executeQuery();
8037   
8038  4 if (resultSet2 != null && resultSet2.next()) {
8039    //If the API ID is different from the one being saved
8040  4 if (apiID != resultSet2.getInt("API_ID")) {
8041    //Check if the provider name and api name is same.
8042  2 if (provider.equals(APIUtil.replaceEmailDomainBack(identifier.getProviderName())) && apiName
8043    .equals(identifier.getApiName())) {
8044   
8045    //Return false since this means we're attaching the scope to another version of the API.
8046  2 return false;
8047    }
8048  0 return true;
8049    } else {
8050  2 return false;
8051    }
8052    }
8053    }
8054    } catch (SQLException e) {
8055  0 handleException("Failed to check Scope Key availability : " + scopeKey, e);
8056    } finally {
8057  38 APIMgtDBUtil.closeAllConnections(prepStmt2, null, resultSet2);
8058  38 APIMgtDBUtil.closeAllConnections(prepStmt, connection, resultSet);
8059    }
8060  34 return false;
8061    }
8062   
 
8063  238 toggle public boolean isDuplicateContextTemplate(String contextTemplate) throws APIManagementException {
8064  238 Connection conn = null;
8065  238 ResultSet resultSet = null;
8066  238 PreparedStatement ps = null;
8067   
8068  238 String sqlQuery = SQLConstants.GET_CONTEXT_TEMPLATE_COUNT_SQL;
8069  238 try {
8070  238 conn = APIMgtDBUtil.getConnection();
8071  238 ps = conn.prepareStatement(sqlQuery);
8072  238 ps.setString(1, contextTemplate);
8073   
8074  238 resultSet = ps.executeQuery();
8075  238 if (resultSet.next()) {
8076  238 int count = resultSet.getInt("CTX_COUNT");
8077  238 return count > 0;
8078    }
8079    } catch (SQLException e) {
8080  0 handleException("Failed to count contexts which match " + contextTemplate, e);
8081    } finally {
8082  238 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
8083    }
8084  0 return false;
8085    }
8086   
8087    /**
8088    * retrieve list of API names which matches given context
8089    *
8090    * @param contextTemplate context template
8091    * @return list of API names
8092    * @throws APIManagementException
8093    */
 
8094  0 toggle public List<String> getAPINamesMatchingContext(String contextTemplate) throws APIManagementException {
8095  0 Connection conn = null;
8096  0 ResultSet resultSet = null;
8097  0 PreparedStatement ps = null;
8098  0 List<String> nameList = new ArrayList<String>();
8099   
8100  0 String sqlQuery = SQLConstants.GET_API_NAMES_MATCHES_CONTEXT;
8101  0 try {
8102  0 conn = APIMgtDBUtil.getConnection();
8103  0 ps = conn.prepareStatement(sqlQuery);
8104  0 ps.setString(1, contextTemplate);
8105   
8106  0 resultSet = ps.executeQuery();
8107  0 while (resultSet.next()) {
8108  0 nameList.add(resultSet.getString("API_NAME"));
8109    }
8110    } catch (SQLException e) {
8111  0 handleException("Failed to get API names matches context " + contextTemplate, e);
8112    } finally {
8113  0 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
8114    }
8115  0 return nameList;
8116    }
8117   
8118    /**
8119    * @param consumerKey
8120    * @return
8121    */
 
8122  0 toggle public boolean isMappingExistsforConsumerKey(String consumerKey) throws APIManagementException {
8123  0 Connection conn = null;
8124  0 ResultSet resultSet = null;
8125  0 PreparedStatement ps = null;
8126   
8127  0 String sqlQuery = SQLConstants.GET_APPLICATION_MAPPING_FOR_CONSUMER_KEY_SQL;
8128  0 try {
8129  0 conn = APIMgtDBUtil.getConnection();
8130  0 ps = conn.prepareStatement(sqlQuery);
8131  0 ps.setString(1, consumerKey);
8132   
8133  0 resultSet = ps.executeQuery();
8134    // We only expect one result.
8135  0 if (resultSet.next()) {
8136  0 String applicationId = resultSet.getString("APPLICATION_ID");
8137  0 return (applicationId != null && !applicationId.isEmpty());
8138    }
8139    } catch (SQLException e) {
8140  0 handleException("Failed to get Application ID by consumerKey ", e);
8141    } finally {
8142  0 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
8143    }
8144  0 return false;
8145    }
8146   
8147    /**
8148    * @param applicationId
8149    * @param keyType
8150    * @return
8151    */
 
8152  866 toggle public String getConsumerkeyByApplicationIdAndKeyType(String applicationId, String keyType)
8153    throws APIManagementException {
8154  866 Connection conn = null;
8155  866 ResultSet resultSet = null;
8156  866 PreparedStatement ps = null;
8157  866 String consumerKey = null;
8158  866 try {
8159  866 conn = APIMgtDBUtil.getConnection();
8160   
8161  866 String sqlQuery = SQLConstants.GET_CONSUMER_KEY_BY_APPLICATION_AND_KEY_SQL;
8162   
8163  866 ps = conn.prepareStatement(sqlQuery);
8164  866 ps.setInt(1, Integer.parseInt(applicationId));
8165  866 ps.setString(2, keyType);
8166  866 resultSet = ps.executeQuery();
8167   
8168  1166 while (resultSet.next()) {
8169  300 consumerKey = resultSet.getString("CONSUMER_KEY");
8170    }
8171    } catch (SQLException e) {
8172  0 handleException("Failed to get consumer key by applicationId " + applicationId + "and keyType " +
8173    keyType, e);
8174    } finally {
8175  866 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
8176    }
8177  866 return consumerKey;
8178    }
8179   
8180    /**
8181    * Get external APIStores details which are stored in database
8182    *
8183    * @param apiIdentifier API Identifier
8184    * @throws APIManagementException if failed to get external APIStores
8185    */
 
8186  0 toggle public String getLastPublishedAPIVersionFromAPIStore(APIIdentifier apiIdentifier, String storeName)
8187    throws APIManagementException {
8188  0 PreparedStatement ps = null;
8189  0 ResultSet rs = null;
8190  0 Connection conn = null;
8191  0 String version = null;
8192  0 try {
8193  0 conn = APIMgtDBUtil.getConnection();
8194  0 String sqlQuery = SQLConstants.GET_LAST_PUBLISHED_API_VERSION_SQL;
8195  0 ps = conn.prepareStatement(sqlQuery);
8196  0 ps.setString(1, apiIdentifier.getProviderName());
8197  0 ps.setString(2, apiIdentifier.getApiName());
8198  0 ps.setString(3, storeName);
8199  0 rs = ps.executeQuery();
8200  0 while (rs.next()) {
8201  0 version = rs.getString("API_VERSION");
8202    }
8203    } catch (SQLException e) {
8204  0 handleException("Error while getting External APIStore details from the database for the API : " +
8205    apiIdentifier.getApiName() + '-' + apiIdentifier.getVersion(), e);
8206   
8207    } finally {
8208  0 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
8209    }
8210  0 return version;
8211    }
8212   
 
8213  300 toggle private String getScopeString(List<String> scopes) {
8214  300 return StringUtils.join(scopes, " ");
8215    }
8216   
8217    /**
8218    * Find all active access tokens of a given user.
8219    *
8220    * @param username - Username of the user
8221    * @return - The set of active access tokens of the user.
8222    */
 
8223  35 toggle public Set<String> getActiveAccessTokensOfUser(String username) throws APIManagementException {
8224   
8225  35 Connection conn = null;
8226  35 ResultSet resultSet = null;
8227  35 PreparedStatement ps = null;
8228   
8229  35 Set<String> tokens = null;
8230   
8231  35 String accessTokenStoreTable = APIConstants.ACCESS_TOKEN_STORE_TABLE;
8232  35 accessTokenStoreTable = getAccessTokenStoreTableNameOfUserId(username, accessTokenStoreTable);
8233   
8234  35 int tenantId = IdentityTenantUtil.getTenantIdOfUser(username);
8235  35 String userStoreDomain = IdentityUtil.extractDomainFromName(username).toUpperCase();
8236  35 if (StringUtils.isEmpty(userStoreDomain)) {
8237  0 userStoreDomain = IdentityUtil.getPrimaryDomainName();
8238    } else {
8239    //IdentityUtil doesn't have a function to remove the domain name from the username. Using the UserCoreUtil.
8240  35 username = UserCoreUtil.removeDomainFromName(username);
8241    }
8242   
8243  35 try {
8244  35 conn = APIMgtDBUtil.getConnection();
8245  35 String sqlQuery = SQLConstants.GET_ACTIVE_TOKENS_OF_USER_PREFIX + accessTokenStoreTable + SQLConstants
8246    .GET_ACTIVE_TOKENS_OF_USER_SUFFIX;
8247   
8248  35 ps = conn.prepareStatement(sqlQuery);
8249  35 ps.setString(1, MultitenantUtils.getTenantAwareUsername(username));
8250  35 ps.setInt(2, tenantId);
8251  35 ps.setString(3, userStoreDomain.toLowerCase());
8252  35 resultSet = ps.executeQuery();
8253  35 tokens = new HashSet<String>();
8254  35 while (resultSet.next()) {
8255  0 tokens.add(APIUtil.decryptToken(resultSet.getString("ACCESS_TOKEN")));
8256    }
8257    } catch (SQLException e) {
8258  0 handleException("Failed to get active access tokens of user " + username, e);
8259    } catch (CryptoException e) {
8260  0 handleException("Token decryption failed of an active access token of user " + username, e);
8261    } finally {
8262  35 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
8263    }
8264  35 return tokens;
8265    }
8266   
8267    // public TokenGenerator getTokenGenerator() {
8268    // return tokenGenerator;
8269    // }
8270   
 
8271  335 toggle private String getAccessTokenStoreTableNameOfUserId(String userId, String accessTokenStoreTable)
8272    throws APIManagementException {
8273  335 if (APIUtil.checkAccessTokenPartitioningEnabled() && APIUtil.checkUserNameAssertionEnabled()) {
8274  0 return APIUtil.getAccessTokenStoreTableFromUserId(userId);
8275    }
8276  335 return accessTokenStoreTable;
8277    }
8278   
 
8279  2 toggle private String getAccessTokenStoreTableFromAccessToken(String accessToken, String accessTokenStoreTable)
8280    throws APIManagementException {
8281  2 if (APIUtil.checkAccessTokenPartitioningEnabled() && APIUtil.checkUserNameAssertionEnabled()) {
8282  0 return APIUtil.getAccessTokenStoreTableFromAccessToken(accessToken);
8283    }
8284  2 return accessTokenStoreTable;
8285    }
8286   
8287    /**
8288    * This method will fetch all alerts type that is available in AM_ALERT_TYPES.
8289    *
8290    * @param stakeHolder the name of the stakeholder. whether its "subscriber", "publisher" or
8291    * "admin-dashboard"
8292    * @return List of alert types
8293    * @throws APIManagementException
8294    */
 
8295  0 toggle public HashMap<Integer, String> getAllAlertTypesByStakeHolder(String stakeHolder) throws APIManagementException {
8296  0 Connection conn = null;
8297  0 ResultSet resultSet = null;
8298  0 PreparedStatement ps = null;
8299  0 HashMap<Integer, String> map = new HashMap<Integer, String>();
8300   
8301  0 try {
8302  0 conn = APIMgtDBUtil.getConnection();
8303  0 String sqlQuery;
8304  0 if (stakeHolder.equals("admin-dashboard")) {
8305  0 sqlQuery = SQLConstants.GET_ALL_ALERT_TYPES_FOR_ADMIN;
8306  0 ps = conn.prepareStatement(sqlQuery);
8307    } else {
8308  0 sqlQuery = SQLConstants.GET_ALL_ALERT_TYPES;
8309  0 ps = conn.prepareStatement(sqlQuery);
8310  0 ps.setString(1, stakeHolder);
8311    }
8312   
8313  0 resultSet = ps.executeQuery();
8314  0 while (resultSet.next()) {
8315  0 map.put(resultSet.getInt(1), resultSet.getString(2));
8316    }
8317    } catch (SQLException e) {
8318  0 handleException("Failed to retrieve alert types ", e);
8319    } finally {
8320  0 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
8321    }
8322  0 return map;
8323    }
8324   
8325    /**
8326    * @param userName user name with tenant domain ex: admin@carbon.super
8327    * @param stakeHolder value "p" for publisher value "s" for subscriber value "a" for admin
8328    * @return map of saved values of alert types.
8329    * @throws APIManagementException
8330    */
 
8331  0 toggle public List<Integer> getSavedAlertTypesIdsByUserNameAndStakeHolder(String userName, String stakeHolder) throws APIManagementException {
8332  0 Connection conn = null;
8333  0 ResultSet resultSet = null;
8334  0 PreparedStatement ps = null;
8335  0 List<Integer> list = new ArrayList<Integer>();
8336   
8337  0 try {
8338  0 String sqlQuery;
8339  0 conn = APIMgtDBUtil.getConnection();
8340  0 sqlQuery = SQLConstants.GET_SAVED_ALERT_TYPES_BY_USERNAME;
8341  0 ps = conn.prepareStatement(sqlQuery);
8342  0 ps.setString(1, userName);
8343  0 ps.setString(2, stakeHolder);
8344  0 resultSet = ps.executeQuery();
8345  0 while (resultSet.next()) {
8346  0 list.add(resultSet.getInt(1));
8347    }
8348    } catch (SQLException e) {
8349  0 handleException("Failed to retrieve saved alert types by user name. ", e);
8350    } finally {
8351  0 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
8352    }
8353  0 return list;
8354    }
8355   
8356    /**
8357    * This method will retrieve saved emails list by user name and stakeholder.
8358    *
8359    * @param userName user name.
8360    * @param stakeHolder "publisher" , "subscriber" or "admin-dashboard"
8361    * @return
8362    * @throws APIManagementException
8363    */
 
8364  0 toggle public List<String> retrieveSavedEmailList(String userName, String stakeHolder) throws APIManagementException {
8365   
8366  0 Connection conn = null;
8367  0 ResultSet resultSet = null;
8368  0 PreparedStatement ps = null;
8369  0 List<String> list = new ArrayList<String>();
8370   
8371  0 try {
8372  0 String sqlQuery;
8373  0 conn = APIMgtDBUtil.getConnection();
8374  0 sqlQuery = SQLConstants.GET_SAVED_ALERT_EMAILS;
8375  0 ps = conn.prepareStatement(sqlQuery);
8376  0 ps.setString(1, userName);
8377  0 ps.setString(2, stakeHolder);
8378  0 resultSet = ps.executeQuery();
8379  0 while (resultSet.next()) {
8380  0 list.add(resultSet.getString(1));
8381    }
8382    } catch (SQLException e) {
8383  0 handleException("Failed to retrieve saved alert types by user name. ", e);
8384    } finally {
8385  0 APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
8386    }
8387  0 return list;
8388   
8389    }
8390   
8391    /**
8392    * This method will delete all email alert subscriptions details from tables
8393    *
8394    * @param userName
8395    * @param agent whether its publisher or store or admin dash board.
8396    */
 
8397  0 toggle public void unSubscribeAlerts(String userName, String agent) throws APIManagementException, SQLException {
8398   
8399  0 Connection connection;
8400  0 PreparedStatement ps = null;
8401  0 ResultSet rs = null;
8402  0 connection = APIMgtDBUtil.getConnection();
8403  0 connection.setAutoCommit(false);
8404   
8405  0 try {
8406  0 connection.setAutoCommit(false);
8407  0 String alertTypesQuery = SQLConstants.ADD_ALERT_TYPES_VALUES;
8408   
8409  0 String deleteAlertTypesByUserNameAndStakeHolderQuery = SQLConstants.DELETE_ALERTTYPES_BY_USERNAME_AND_STAKE_HOLDER;
8410   
8411  0 ps = connection.prepareStatement(deleteAlertTypesByUserNameAndStakeHolderQuery);
8412  0 ps.setString(1, userName);
8413  0 ps.setString(2, agent);
8414  0 ps.executeUpdate();
8415   
8416  0 String getEmailListIdByUserNameAndStakeHolderQuery = SQLConstants.GET_EMAILLISTID_BY_USERNAME_AND_STAKEHOLDER;
8417  0 ps = connection.prepareStatement(getEmailListIdByUserNameAndStakeHolderQuery);
8418  0 ps.setString(1, userName);
8419  0 ps.setString(2, agent);
8420  0 rs = ps.executeQuery();
8421  0 int emailListId = 0;
8422  0 while (rs.next()) {
8423  0 emailListId = rs.getInt(1);
8424    }
8425  0 if (emailListId != 0) {
8426  0 String deleteEmailListDetailsByEmailListId = SQLConstants.DELETE_EMAILLIST_BY_EMAIL_LIST_ID;
8427  0 ps = connection.prepareStatement(deleteEmailListDetailsByEmailListId);
8428  0 ps.setInt(1, emailListId);
8429  0 ps.executeUpdate();
8430   
8431    }
8432   
8433  0 connection.commit();
8434   
8435    } catch (SQLException e) {
8436  0 handleException("Failed to delete alert email data.", e);
8437    } finally {
8438  0 APIMgtDBUtil.closeAllConnections(ps, connection, rs);
8439   
8440    }
8441   
8442   
8443    }
8444   
8445    /**
8446    * @param userName User name.
8447    * @param emailList Comma separated email list.
8448    * @param alertTypesIDList Comma separated alert types list.
8449    * @param stakeHolder if pram value = p we assume those changes from publisher if param value = s those data belongs to
8450    * subscriber.
8451    * @throws APIManagementException
8452    * @throws SQLException
8453    */
 
8454  0 toggle public void addAlertTypesConfigInfo(String userName, String emailList, String alertTypesIDList, String stakeHolder)
8455    throws APIManagementException, SQLException {
8456   
8457  0 Connection connection;
8458  0 PreparedStatement ps = null;
8459  0 ResultSet rs = null;
8460  0 connection = APIMgtDBUtil.getConnection();
8461  0 connection.setAutoCommit(false);
8462  0 try {
8463   
8464  0 String alertTypesQuery = SQLConstants.ADD_ALERT_TYPES_VALUES;
8465   
8466  0 String deleteAlertTypesByUserNameAndStakeHolderQuery = SQLConstants.DELETE_ALERTTYPES_BY_USERNAME_AND_STAKE_HOLDER;
8467   
8468  0 ps = connection.prepareStatement(deleteAlertTypesByUserNameAndStakeHolderQuery);
8469  0 ps.setString(1, userName);
8470  0 ps.setString(2, stakeHolder);
8471  0 ps.executeUpdate();
8472   
8473  0 if (!StringUtils.isEmpty(alertTypesIDList)) {
8474   
8475  0 List<String> alertTypeIdList = Arrays.asList(alertTypesIDList.split(","));
8476   
8477  0 for (String alertTypeId : alertTypeIdList) {
8478  0 PreparedStatement psAlertTypeId = null;
8479  0 try {
8480  0 psAlertTypeId = connection.prepareStatement(alertTypesQuery);
8481  0 psAlertTypeId.setInt(1, Integer.parseInt(alertTypeId));
8482  0 psAlertTypeId.setString(2, userName);
8483  0 psAlertTypeId.setString(3, stakeHolder);
8484  0 psAlertTypeId.execute();
8485    } catch (SQLException e) {
8486  0 handleException("Error while adding alert types", e);
8487    } finally {
8488  0 APIMgtDBUtil.closeAllConnections(psAlertTypeId, null, null);
8489    }
8490    }
8491   
8492   
8493    }
8494   
8495  0 String getEmailListIdByUserNameAndStakeHolderQuery = SQLConstants.GET_EMAILLISTID_BY_USERNAME_AND_STAKEHOLDER;
8496  0 ps = connection.prepareStatement(getEmailListIdByUserNameAndStakeHolderQuery);
8497  0 ps.setString(1, userName);
8498  0 ps.setString(2, stakeHolder);
8499  0 rs = ps.executeQuery();
8500  0 int emailListId = 0;
8501  0 while (rs.next()) {
8502  0 emailListId = rs.getInt(1);
8503    }
8504  0 if (emailListId != 0) {
8505  0 String deleteEmailListDetailsByEmailListId = SQLConstants.DELETE_EMAILLIST_BY_EMAIL_LIST_ID;
8506  0 ps = connection.prepareStatement(deleteEmailListDetailsByEmailListId);
8507  0 ps.setInt(1, emailListId);
8508  0 ps.executeUpdate();
8509   
8510  0 if (!StringUtils.isEmpty(emailList)) {
8511   
8512  0 List<String> extractedEmailList = Arrays.asList(emailList.split(","));
8513   
8514  0 String saveEmailListDetailsQuery = SQLConstants.SAVE_EMAIL_LIST_DETAILS_QUERY;
8515   
8516  0 for (String email : extractedEmailList) {
8517  0 PreparedStatement extractedEmailListPs = null;
8518  0 try {
8519  0 extractedEmailListPs = connection.prepareStatement(saveEmailListDetailsQuery);
8520  0 extractedEmailListPs.setInt(1, emailListId);
8521  0 extractedEmailListPs.setString(2, email);
8522  0 extractedEmailListPs.execute();
8523    } catch (SQLException e) {
8524  0 handleException("Error while save email list.", e);
8525    } finally {
8526  0 APIMgtDBUtil.closeAllConnections(extractedEmailListPs, null, null);
8527    }
8528    }
8529   
8530    }
8531   
8532    } else {
8533   
8534  0 String emailListSaveQuery = SQLConstants.ADD_ALERT_EMAIL_LIST;
8535   
8536  0 String dbProductName = connection.getMetaData().getDatabaseProductName();
8537   
8538  0 ps = connection.prepareStatement(emailListSaveQuery, new String[]{DBUtils.
8539    getConvertedAutoGeneratedColumnName(dbProductName, "EMAIL_LIST_ID")});
8540   
8541  0 ps.setString(1, userName);
8542  0 ps.setString(2, stakeHolder);
8543  0 ps.execute();
8544   
8545  0 rs = ps.getGeneratedKeys();
8546   
8547  0 if (rs.next()) {
8548  0 int generatedEmailIdList = rs.getInt(1);
8549  0 if (!StringUtils.isEmpty(emailList)) {
8550   
8551  0 List<String> extractedEmailList = Arrays.asList(emailList.split(","));
8552   
8553  0 String saveEmailListDetailsQuery = SQLConstants.SAVE_EMAIL_LIST_DETAILS_QUERY;
8554   
8555  0 for (String email : extractedEmailList) {
8556  0 PreparedStatement elseExtractedEmailListPS = null;
8557  0 try {
8558  0 elseExtractedEmailListPS = connection.prepareStatement(saveEmailListDetailsQuery);
8559  0 elseExtractedEmailListPS.setInt(1, generatedEmailIdList);
8560  0 elseExtractedEmailListPS.setString(2, email);
8561  0 elseExtractedEmailListPS.execute();
8562    } catch (SQLException e) {
8563  0 handleException("Error while save email list.", e);
8564    } finally {
8565  0 APIMgtDBUtil.closeAllConnections(elseExtractedEmailListPS, null, null);
8566    }
8567    }
8568   
8569    }
8570    }
8571   
8572    }
8573  0 connection.commit();
8574   
8575    } catch (SQLException e) {
8576  0 handleException("Failed to save alert preferences", e);
8577    } finally {
8578  0 APIMgtDBUtil.closeAllConnections(ps, connection, rs);
8579    }
8580    }
8581   
8582    /**
8583    * Add a Application level throttling policy to database
8584    *
8585    * @param policy policy object defining the throttle policy
8586    * @throws APIManagementException
8587    */
 
8588  20 toggle public void addApplicationPolicy(ApplicationPolicy policy) throws APIManagementException {
8589  20 Connection conn = null;
8590  20 PreparedStatement policyStatement = null;
8591  20 boolean hasCustomAttrib = false;
8592  20 try {
8593  20 if (policy.getCustomAttributes() != null) {
8594  0 hasCustomAttrib = true;
8595    }
8596  20 conn = APIMgtDBUtil.getConnection();
8597  20 conn.setAutoCommit(false);
8598  20 String addQuery = SQLConstants.INSERT_APPLICATION_POLICY_SQL;
8599  20 if (hasCustomAttrib) {
8600  0 addQuery = SQLConstants.INSERT_APPLICATION_POLICY_WITH_CUSTOM_ATTRIB_SQL;
8601    }
8602  20 policyStatement = conn.prepareStatement(addQuery);
8603  20 setCommonParametersForPolicy(policyStatement, policy);
8604  20 if (hasCustomAttrib) {
8605  0 policyStatement.setBlob(12, new ByteArrayInputStream(policy.getCustomAttributes()));
8606    }
8607  20 policyStatement.executeUpdate();
8608   
8609  20 conn.commit();
8610    } catch (SQLException e) {
8611  0 if (conn != null) {
8612  0 try {
8613  0 conn.rollback();
8614    } catch (SQLException ex) {
8615   
8616    // Rollback failed. Exception will be thrown later for upper exception
8617  0 log.error("Failed to rollback the add Application Policy: " + policy.toString(), ex);
8618    }
8619    }
8620  0 handleException("Failed to add Application Policy: " + policy, e);
8621    } finally {
8622  20 APIMgtDBUtil.closeAllConnections(policyStatement, conn, null);
8623    }
8624    }
8625   
8626    /**
8627    * Add a Subscription level throttling policy to database
8628    *
8629    * @param policy policy object defining the throttle policy
8630    * @throws APIManagementException
8631    */
 
8632  25 toggle public void addSubscriptionPolicy(SubscriptionPolicy policy) throws APIManagementException {
8633  25 Connection conn = null;
8634  25 PreparedStatement policyStatement = null;
8635  25 boolean hasCustomAttrib = false;
8636   
8637  25 try {
8638  25 if (policy.getCustomAttributes() != null) {
8639  0 hasCustomAttrib = true;
8640    }
8641  25 conn = APIMgtDBUtil.getConnection();
8642  25 conn.setAutoCommit(false);
8643  25 String addQuery = SQLConstants.INSERT_SUBSCRIPTION_POLICY_SQL;
8644  25 if (hasCustomAttrib) {
8645  0 addQuery = SQLConstants.INSERT_SUBSCRIPTION_POLICY_WITH_CUSTOM_ATTRIB_SQL;
8646    }
8647  25 policyStatement = conn.prepareStatement(addQuery);
8648  25 setCommonParametersForPolicy(policyStatement, policy);
8649  25 policyStatement.setInt(12, policy.getRateLimitCount());
8650  25 policyStatement.setString(13, policy.getRateLimitTimeUnit());
8651  25 policyStatement.setBoolean(14, policy.isStopOnQuotaReach());
8652  25 policyStatement.setString(15, policy.getBillingPlan());
8653  25 if (hasCustomAttrib) {
8654  0 policyStatement.setBytes(16, policy.getCustomAttributes());
8655    }
8656  25 policyStatement.executeUpdate();
8657   
8658  25 conn.commit();
8659    } catch (SQLException e) {
8660  0 if (conn != null) {
8661  0 try {
8662  0 conn.rollback();
8663    } catch (SQLException ex) {
8664   
8665    // Rollback failed. Exception will be thrown later for upper exception
8666  0 log.error("Failed to rollback the add Subscription Policy: " + policy.toString(), ex);
8667    }
8668    }
8669  0 handleException("Failed to add Subscription Policy: " + policy, e);
8670    } finally {
8671  25 APIMgtDBUtil.closeAllConnections(policyStatement, conn, null);
8672    }
8673    }
8674   
8675    /**
8676    * Wrapper method for {@link #addAPIPolicy(APIPolicy, Connection)} to add
8677    * API Policy without managing the database connection manually.
8678    *
8679    * @param policy policy object to add
8680    * @throws APIManagementException
8681    */
 
8682  22 toggle public APIPolicy addAPIPolicy(APIPolicy policy) throws APIManagementException {
8683  22 Connection connection = null;
8684   
8685  22 try {
8686  22 connection = APIMgtDBUtil.getConnection();
8687  22 connection.setAutoCommit(false);
8688  22 addAPIPolicy(policy, connection);
8689  22 connection.commit();
8690    } catch (SQLException e) {
8691  0 if (connection != null) {
8692  0 try {
8693  0 connection.rollback();
8694    } catch (SQLException ex) {
8695   
8696    // Rollback failed. Exception will be thrown later for upper exception
8697  0 log.error("Failed to rollback the add Api Policy: " + policy.toString(), ex);
8698    }
8699    }
8700  0 handleException("Failed to add Api Policy: " + policy, e);
8701    } finally {
8702  22 APIMgtDBUtil.closeAllConnections(null, connection, null);
8703    }
8704  22 return policy;
8705    }
8706   
8707    /**
8708    * Add a API level throttling policy to database.
8709    * <p>
8710    * If valid policy Id (not -1) is present in the <code>policy</code> object,
8711    * policy will be inserted with that policy Id.
8712    * Otherwise policy Id will be auto incremented.
8713    * </p>
8714    *
8715    * @param policy policy object defining the throttle policy
8716    * @throws SQLException
8717    */
 
8718  22 toggle private void addAPIPolicy(APIPolicy policy, Connection conn) throws SQLException {
8719  22 ResultSet resultSet = null;
8720  22 PreparedStatement policyStatement = null;
8721  22 String addQuery = SQLConstants.ThrottleSQLConstants.INSERT_API_POLICY_SQL;
8722  22 int policyId;
8723   
8724  22 try {
8725  22 String dbProductName = conn.getMetaData().getDatabaseProductName();
8726  22 policyStatement = conn.prepareStatement(addQuery,
8727    new String[]{DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "POLICY_ID")});
8728  22 setCommonParametersForPolicy(policyStatement, policy);
8729  22 policyStatement.setString(12, policy.getUserLevel());
8730  22 policyStatement.executeUpdate();
8731  22 resultSet = policyStatement.getGeneratedKeys(); // Get the inserted POLICY_ID (auto incremented value)
8732   
8733    // Returns only single row
8734  22 if (resultSet.next()) {
8735   
8736    /*
8737    * H2 doesn't return generated keys when key is provided (not generated).
8738    Therefore policyId should be policy parameter's policyId when it is provided.
8739    */
8740  22 policyId = resultSet.getInt(1);
8741  22 List<Pipeline> pipelines = policy.getPipelines();
8742  22 if (pipelines != null) {
8743  0 for (Pipeline pipeline : pipelines) { // add each pipeline data to AM_CONDITION_GROUP table
8744  0 addPipeline(pipeline, policyId, conn);
8745    }
8746    }
8747    }
8748    } finally {
8749  22 APIMgtDBUtil.closeAllConnections(policyStatement, null, resultSet);
8750    }
8751    }
8752   
8753    /**
8754    * Update a API level throttling policy to database.
8755    * <p>
8756    * policy will be inserted with that policy Id.
8757    * </p>
8758    *
8759    * @param policy policy object defining the throttle policy
8760    * @throws SQLException
8761    */
 
8762  0 toggle private void updateAPIPolicy(APIPolicy policy, Connection conn) throws SQLException {
8763  0 ResultSet resultSet = null;
8764  0 PreparedStatement policyStatement = null;
8765  0 String addQuery = SQLConstants.ThrottleSQLConstants.INSERT_API_POLICY_WITH_ID_SQL;
8766  0 int policyId = policy.getPolicyId();
8767   
8768  0 try {
8769  0 Statement st = conn.createStatement();
8770  0 String driverName = conn.getMetaData().getDriverName();
8771  0 if (driverName.contains("MS SQL") || driverName.contains("Microsoft")) {
8772  0 st.executeUpdate("SET IDENTITY_INSERT AM_API_THROTTLE_POLICY ON");
8773    }
8774  0 String dbProductName = conn.getMetaData().getDatabaseProductName();
8775  0 policyStatement = conn.prepareStatement(addQuery,
8776    new String[]{DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "POLICY_ID")});
8777  0 setCommonParametersForPolicy(policyStatement, policy);
8778  0 policyStatement.setString(12, policy.getUserLevel());
8779  0 policyStatement.setBoolean(10, true);
8780  0 policyStatement.setInt(13, policyId);
8781  0 int updatedRawCount = policyStatement.executeUpdate();
8782   
8783  0 if (driverName.contains("MS SQL") || driverName.contains("Microsoft")) {
8784  0 st.executeUpdate("SET IDENTITY_INSERT AM_API_THROTTLE_POLICY OFF");
8785    }
8786   
8787    // Returns only single row
8788  0 if (updatedRawCount > 0) {
8789  0 List<Pipeline> pipelines = policy.getPipelines();
8790  0 if (pipelines != null) {
8791  0 for (Pipeline pipeline : pipelines) { // add each pipeline data to AM_CONDITION_GROUP table
8792  0 addPipeline(pipeline, policyId, conn);
8793    }
8794    }
8795    }
8796    } finally {
8797  0 APIMgtDBUtil.closeAllConnections(policyStatement, null, resultSet);
8798    }
8799    }
8800   
8801    /**
8802    * Add throttling policy pipeline to database
8803    *
8804    * @param pipeline condition pipeline
8805    * @param policyID id of the policy to add pipeline
8806    * @param conn database connection. This should be provided inorder to rollback transaction
8807    * @throws SQLException
8808    */
 
8809  0 toggle private void addPipeline(Pipeline pipeline, int policyID, Connection conn) throws SQLException {
8810  0 PreparedStatement conditionStatement = null;
8811  0 ResultSet rs = null;
8812   
8813  0 try {
8814  0 String sqlAddQuery = SQLConstants.ThrottleSQLConstants.INSERT_CONDITION_GROUP_SQL;
8815  0 List<Condition> conditionList = pipeline.getConditions();
8816   
8817    // Add data to the AM_CONDITION table
8818  0 String dbProductName = conn.getMetaData().getDatabaseProductName();
8819  0 conditionStatement = conn.prepareStatement(sqlAddQuery, new String[]{DBUtils
8820    .getConvertedAutoGeneratedColumnName(dbProductName, "CONDITION_GROUP_ID")});
8821  0 conditionStatement.
8822    setInt(1, policyID);
8823  0 conditionStatement.setString(2, pipeline.getQuotaPolicy().getType());
8824   
8825  0 if (PolicyConstants.REQUEST_COUNT_TYPE.equals(pipeline.getQuotaPolicy().getType())) {
8826  0 conditionStatement.setLong(3,
8827    ((RequestCountLimit) pipeline.getQuotaPolicy().getLimit()).getRequestCount());
8828  0 conditionStatement.setString(4, null);
8829  0 } else if (PolicyConstants.BANDWIDTH_TYPE.equals(pipeline.getQuotaPolicy().getType())) {
8830  0 BandwidthLimit limit = (BandwidthLimit) pipeline.getQuotaPolicy().getLimit();
8831  0 conditionStatement.setLong(3, limit.getDataAmount());
8832  0 conditionStatement.setString(4, limit.getDataUnit());
8833    }
8834   
8835  0 conditionStatement.setLong(5, pipeline.getQuotaPolicy().getLimit().getUnitTime());
8836  0 conditionStatement.setString(6, pipeline.getQuotaPolicy().getLimit().getTimeUnit());
8837  0 conditionStatement.setString(7, pipeline.getDescription());
8838  0 conditionStatement.executeUpdate();
8839  0 rs = conditionStatement.getGeneratedKeys();
8840   
8841    // Add Throttling parameters which have multiple entries
8842  0 if (rs != null && rs.next()) {
8843  0 int pipelineId = rs.getInt(1); // Get the inserted
8844    // CONDITION_GROUP_ID (auto
8845    // incremented value)
8846  0 pipeline.setId(pipelineId);
8847  0 for (Condition condition : conditionList) {
8848  0 if (condition == null) {
8849  0 continue;
8850    }
8851  0 String type = condition.getType();
8852  0 if (PolicyConstants.IP_RANGE_TYPE.equals(type) || PolicyConstants.IP_SPECIFIC_TYPE.equals(type)) {
8853  0 IPCondition ipCondition = (IPCondition) condition;
8854  0 addIPCondition(ipCondition, pipelineId, conn);
8855    }
8856   
8857  0 if (PolicyConstants.HEADER_TYPE.equals(type)) {
8858  0 addHeaderCondition((HeaderCondition) condition, pipelineId, conn);
8859  0 } else if (PolicyConstants.QUERY_PARAMETER_TYPE.equals(type)) {
8860  0 addQueryParameterCondition((QueryParameterCondition) condition, pipelineId, conn);
8861  0 } else if (PolicyConstants.JWT_CLAIMS_TYPE.equals(type)) {
8862  0 addJWTClaimsCondition((JWTClaimsCondition) condition, pipelineId, conn);
8863    }
8864    }
8865    }
8866    } finally {
8867  0 APIMgtDBUtil.closeAllConnections(conditionStatement, null, rs);
8868    }
8869    }
8870   
8871    /**
8872    * Add HEADER throttling condition to AM_HEADER_FIELD_CONDITION table
8873    *
8874    * @param headerCondition {@link HeaderCondition} with header fieled and value
8875    * @param pipelineId id of the pipeline which this condition belongs to
8876    * @param conn database connection. This should be provided inorder to rollback transaction
8877    * @throws SQLException
8878    */
 
8879  0 toggle private void addHeaderCondition(HeaderCondition headerCondition, int pipelineId, Connection conn)
8880    throws SQLException {
8881  0 PreparedStatement psHeaderCondition = null;
8882   
8883  0 try {
8884  0 String sqlQuery = SQLConstants.ThrottleSQLConstants.INSERT_HEADER_FIELD_CONDITION_SQL;
8885  0 psHeaderCondition = conn.prepareStatement(sqlQuery);
8886  0 psHeaderCondition.setInt(1, pipelineId);
8887  0 psHeaderCondition.setString(2, headerCondition.getHeaderName());
8888  0 psHeaderCondition.setString(3, headerCondition.getValue());
8889  0 psHeaderCondition.setBoolean(4, headerCondition.isInvertCondition());
8890  0 psHeaderCondition.executeUpdate();
8891    } finally {
8892  0 APIMgtDBUtil.closeAllConnections(psHeaderCondition, null, null);
8893    }
8894    }
8895   
8896    /**
8897    * Add QUERY throttling condition to AM_QUERY_PARAMETER_CONDITION table
8898    *
8899    * @param queryParameterCondition {@link QueryParameterCondition} with parameter name and value
8900    * @param pipelineId id of the pipeline which this condition belongs to
8901    * @param conn database connection. This should be provided inorder to rollback transaction
8902    * @throws SQLException
8903    */
 
8904  0 toggle private void addQueryParameterCondition(QueryParameterCondition queryParameterCondition, int pipelineId,
8905    Connection conn) throws SQLException {
8906  0 PreparedStatement psQueryParameterCondition = null;
8907   
8908  0 try {
8909  0 String sqlQuery = SQLConstants.ThrottleSQLConstants.INSERT_QUERY_PARAMETER_CONDITION_SQL;
8910  0 psQueryParameterCondition = conn.prepareStatement(sqlQuery);
8911  0 psQueryParameterCondition.setInt(1, pipelineId);
8912  0 psQueryParameterCondition.setString(2, queryParameterCondition.getParameter());
8913  0 psQueryParameterCondition.setString(3, queryParameterCondition.getValue());
8914  0 psQueryParameterCondition.setBoolean(4, queryParameterCondition.isInvertCondition());
8915  0 psQueryParameterCondition.executeUpdate();
8916    } finally {
8917  0 APIMgtDBUtil.closeAllConnections(psQueryParameterCondition, null, null);
8918    }
8919    }
8920   
 
8921  0 toggle private void addIPCondition(IPCondition ipCondition, int pipelineId, Connection conn) throws SQLException {
8922  0 PreparedStatement statementIPCondition = null;
8923   
8924  0 try {
8925  0 String sqlQuery = SQLConstants.ThrottleSQLConstants.INSERT_IP_CONDITION_SQL;
8926   
8927  0 statementIPCondition = conn.prepareStatement(sqlQuery);
8928  0 String startingIP = ipCondition.getStartingIP();
8929  0 String endingIP = ipCondition.getEndingIP();
8930  0 String specificIP = ipCondition.getSpecificIP();
8931   
8932  0 statementIPCondition.setString(1, startingIP);
8933  0 statementIPCondition.setString(2, endingIP);
8934  0 statementIPCondition.setString(3, specificIP);
8935  0 statementIPCondition.setBoolean(4, ipCondition.isInvertCondition());
8936  0 statementIPCondition.setInt(5, pipelineId);
8937  0 statementIPCondition.executeUpdate();
8938    } finally {
8939  0 APIMgtDBUtil.closeAllConnections(statementIPCondition, null, null);
8940    }
8941    }
8942   
8943    /**
8944    * Add JWTCLAIMS throttling condition to AM_JWT_CLAIM_CONDITION table
8945    *
8946    * @param jwtClaimsCondition {@link JWTClaimsCondition} with claim url and claim attribute
8947    * @param pipelineId id of the pipeline which this condition belongs to
8948    * @param conn database connection. This should be provided inorder to rollback transaction
8949    * @throws SQLException
8950    */
 
8951  0 toggle private void addJWTClaimsCondition(JWTClaimsCondition jwtClaimsCondition, int pipelineId, Connection conn)
8952    throws SQLException {
8953  0 PreparedStatement psJWTClaimsCondition = null;
8954   
8955  0 try {
8956  0 String sqlQuery = SQLConstants.ThrottleSQLConstants.INSERT_JWT_CLAIM_CONDITION_SQL;
8957  0 psJWTClaimsCondition = conn.prepareStatement(sqlQuery);
8958  0 psJWTClaimsCondition.setInt(1, pipelineId);
8959  0 psJWTClaimsCondition.setString(2, jwtClaimsCondition.getClaimUrl());
8960  0 psJWTClaimsCondition.setString(3, jwtClaimsCondition.getAttribute());
8961  0 psJWTClaimsCondition.setBoolean(4, jwtClaimsCondition.isInvertCondition());
8962  0 psJWTClaimsCondition.executeUpdate();
8963    } finally {
8964  0 APIMgtDBUtil.closeAllConnections(psJWTClaimsCondition, null, null);
8965    }
8966    }
8967   
8968    /**
8969    * Add a Global level throttling policy to database
8970    *
8971    * @param policy Global Policy
8972    * @throws APIManagementException
8973    */
 
8974  0 toggle public void addGlobalPolicy(GlobalPolicy policy) throws APIManagementException {
8975  0 Connection conn = null;
8976  0 PreparedStatement policyStatement = null;
8977  0 try {
8978  0 conn = APIMgtDBUtil.getConnection();
8979  0 conn.setAutoCommit(false);
8980  0 String addQuery = SQLConstants.INSERT_GLOBAL_POLICY_SQL;
8981  0 policyStatement = conn.prepareStatement(addQuery);
8982  0 policyStatement.setString(1, policy.getPolicyName());
8983  0 policyStatement.setInt(2, policy.getTenantId());
8984  0 policyStatement.setString(3, policy.getKeyTemplate());
8985  0 policyStatement.setString(4, policy.getDescription());
8986   
8987  0 InputStream siddhiQueryInputStream;
8988  0 byte[] byteArray = policy.getSiddhiQuery().getBytes(Charset.defaultCharset());
8989  0 int lengthOfBytes = byteArray.length;
8990  0 siddhiQueryInputStream = new ByteArrayInputStream(byteArray);
8991  0 policyStatement.setBinaryStream(5, siddhiQueryInputStream, lengthOfBytes);
8992  0 policyStatement.setBoolean(6, false);
8993  0 policyStatement.setString(7, UUID.randomUUID().toString());
8994  0 policyStatement.executeUpdate();
8995  0 conn.commit();
8996    } catch (SQLException e) {
8997  0 if (conn != null) {
8998  0 try {
8999  0 conn.rollback();
9000    } catch (SQLException ex) {
9001   
9002    // rollback failed. exception will be thrown later for upper exception
9003  0 log.error("Failed to rollback the add Global Policy: " + policy.toString(), ex);
9004    }
9005    }
9006  0 handleException("Failed to add Global Policy: " + policy, e);
9007    } finally {
9008  0 APIMgtDBUtil.closeAllConnections(policyStatement, conn, null);
9009    }
9010    }
9011   
9012    /**
9013    * Retrieves global policy key templates for the given tenantID
9014    *
9015    * @param tenantID tenant id
9016    * @return list of KeyTemplates
9017    * @throws APIManagementException
9018    */
 
9019  0 toggle public List<String> getGlobalPolicyKeyTemplates(int tenantID) throws APIManagementException {
9020   
9021  0 List<String> keyTemplates = new ArrayList<String>();
9022  0 Connection conn = null;
9023  0 PreparedStatement ps = null;
9024  0 ResultSet rs = null;
9025  0 String sqlQuery = null;
9026   
9027  0 try {
9028  0 conn = APIMgtDBUtil.getConnection();
9029   
9030  0 sqlQuery = SQLConstants.GET_GLOBAL_POLICY_KEY_TEMPLATES;
9031   
9032  0 ps = conn.prepareStatement(sqlQuery);
9033  0 ps.setInt(1, tenantID);
9034  0 rs = ps.executeQuery();
9035  0 while (rs.next()) {
9036  0 keyTemplates.add(rs.getString(ThrottlePolicyConstants.COLUMN_KEY_TEMPLATE));
9037    }
9038   
9039    } catch (SQLException e) {
9040  0 handleException("Error while executing SQL to get GLOBAL_POLICY_KEY_TEMPLATES", e);
9041    } finally {
9042  0 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
9043    }
9044  0 return keyTemplates;
9045    }
9046   
9047    /**
9048    * Returns true if the key template exist in DB
9049    *
9050    * @param policy Global Policy
9051    * @return true if key template already exists
9052    * @throws APIManagementException
9053    */
 
9054  0 toggle public boolean isKeyTemplatesExist(GlobalPolicy policy) throws APIManagementException {
9055   
9056  0 Connection conn = null;
9057  0 PreparedStatement ps = null;
9058  0 ResultSet rs = null;
9059  0 String sqlQuery = null;
9060   
9061  0 try {
9062  0 conn = APIMgtDBUtil.getConnection();
9063   
9064  0 sqlQuery = SQLConstants.GET_GLOBAL_POLICY_KEY_TEMPLATE;
9065   
9066  0 ps = conn.prepareStatement(sqlQuery);
9067  0 ps.setInt(1, policy.getTenantId());
9068  0 ps.setString(2, policy.getKeyTemplate());
9069  0 ps.setString(3, policy.getPolicyName());
9070  0 rs = ps.executeQuery();
9071  0 if (rs.next()) {
9072  0 return true;
9073    }
9074   
9075    } catch (SQLException e) {
9076  0 handleException("Error while executing SQL to get GLOBAL_POLICY_KEY_TEMPLATE", e);
9077    } finally {
9078  0 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
9079    }
9080  0 return false;
9081    }
9082   
9083    /**
9084    * Removes a throttling policy from the database
9085    *
9086    * @param policyLevel level of the policy to be deleted
9087    * @param policyName name of the policy
9088    * @param tenantId used to get the tenant id
9089    * @throws APIManagementException
9090    */
 
9091  0 toggle public void removeThrottlePolicy(String policyLevel, String policyName, int tenantId)
9092    throws APIManagementException {
9093  0 Connection connection = null;
9094  0 PreparedStatement deleteStatement = null;
9095  0 String query = null;
9096   
9097  0 if (PolicyConstants.POLICY_LEVEL_APP.equals(policyLevel)) {
9098  0 query = SQLConstants.DELETE_APPLICATION_POLICY_SQL;
9099  0 } else if (PolicyConstants.POLICY_LEVEL_SUB.equals(policyLevel)) {
9100  0 query = SQLConstants.DELETE_SUBSCRIPTION_POLICY_SQL;
9101  0 } else if (PolicyConstants.POLICY_LEVEL_API.equals(policyLevel)) {
9102  0 query = SQLConstants.ThrottleSQLConstants.DELETE_API_POLICY_SQL;
9103  0 } else if (PolicyConstants.POLICY_LEVEL_GLOBAL.equals(policyLevel)) {
9104  0 query = SQLConstants.DELETE_GLOBAL_POLICY_SQL;
9105    }
9106   
9107  0 try {
9108  0 connection = APIMgtDBUtil.getConnection();
9109  0 connection.setAutoCommit(false);
9110  0 deleteStatement = connection.prepareStatement(query);
9111  0 deleteStatement.setInt(1, tenantId);
9112  0 deleteStatement.setString(2, policyName);
9113  0 deleteStatement.executeUpdate();
9114  0 connection.commit();
9115    } catch (SQLException e) {
9116  0 handleException("Failed to remove policy " + policyLevel + '-' + policyName + '-' + tenantId, e);
9117    } finally {
9118  0 APIMgtDBUtil.closeAllConnections(deleteStatement, connection, null);
9119    }
9120    }
9121   
9122    /**
9123    * Get API level policies. Result only contains basic details of the policy,
9124    * it doesn't contain pipeline information.
9125    *
9126    * @param tenantID policies are selected using tenantID
9127    * @return APIPolicy ArrayList
9128    * @throws APIManagementException
9129    */
 
9130  0 toggle public APIPolicy[] getAPIPolicies(int tenantID) throws APIManagementException {
9131  0 List<APIPolicy> policies = new ArrayList<APIPolicy>();
9132  0 Connection conn = null;
9133  0 PreparedStatement ps = null;
9134  0 ResultSet rs = null;
9135  0 String sqlQuery = SQLConstants.ThrottleSQLConstants.GET_API_POLICIES;
9136   
9137  0 if (forceCaseInsensitiveComparisons) {
9138  0 sqlQuery = SQLConstants.ThrottleSQLConstants.GET_API_POLICIES;
9139    }
9140   
9141  0 try {
9142  0 conn = APIMgtDBUtil.getConnection();
9143  0 ps = conn.prepareStatement(sqlQuery);
9144  0 ps.setInt(1, tenantID);
9145  0 rs = ps.executeQuery();
9146  0 while (rs.next()) {
9147  0 APIPolicy apiPolicy = new APIPolicy(rs.getString(ThrottlePolicyConstants.COLUMN_NAME));
9148  0 setCommonPolicyDetails(apiPolicy, rs);
9149  0 apiPolicy.setUserLevel(rs.getString(ThrottlePolicyConstants.COLUMN_APPLICABLE_LEVEL));
9150   
9151  0 policies.add(apiPolicy);
9152    }
9153    } catch (SQLException e) {
9154  0 handleException("Error while executing SQL", e);
9155    } finally {
9156  0 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
9157    }
9158  0 return policies.toArray(new APIPolicy[policies.size()]);
9159    }
9160   
9161    /**
9162    * Get application level polices
9163    *
9164    * @param tenantID polices are selected only belong to specific tenantID
9165    * @return AppilicationPolicy array list
9166    */
 
9167  137 toggle public ApplicationPolicy[] getApplicationPolicies(int tenantID) throws APIManagementException {
9168  137 List<ApplicationPolicy> policies = new ArrayList<ApplicationPolicy>();
9169  137 Connection conn = null;
9170  137 PreparedStatement ps = null;
9171  137 ResultSet rs = null;
9172   
9173  137 String sqlQuery = SQLConstants.GET_APP_POLICIES;
9174  137 if (forceCaseInsensitiveComparisons) {
9175  137 sqlQuery = SQLConstants.GET_APP_POLICIES;
9176    }
9177   
9178  137 try {
9179  137 conn = APIMgtDBUtil.getConnection();
9180  137 ps = conn.prepareStatement(sqlQuery);
9181  137 ps.setInt(1, tenantID);
9182  137 rs = ps.executeQuery();
9183  685 while (rs.next()) {
9184  548 ApplicationPolicy appPolicy = new ApplicationPolicy(rs.getString(ThrottlePolicyConstants.COLUMN_NAME));
9185  548 setCommonPolicyDetails(appPolicy, rs);
9186  548 policies.add(appPolicy);
9187    }
9188    } catch (SQLException e) {
9189  0 handleException("Error while executing SQL", e);
9190    } finally {
9191  137 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
9192    }
9193  137 return policies.toArray(new ApplicationPolicy[policies.size()]);
9194    }
9195   
9196    /**
9197    * Get all subscription level policeis belongs to specific tenant
9198    *
9199    * @param tenantID tenantID filters the polices belongs to specific tenant
9200    * @return subscriptionPolicy array list
9201    */
 
9202  3148 toggle public SubscriptionPolicy[] getSubscriptionPolicies(int tenantID) throws APIManagementException {
9203  3148 List<SubscriptionPolicy> policies = new ArrayList<SubscriptionPolicy>();
9204  3148 Connection conn = null;
9205  3148 PreparedStatement ps = null;
9206  3148 ResultSet rs = null;
9207   
9208  3148 String sqlQuery = SQLConstants.GET_SUBSCRIPTION_POLICIES;
9209  3148 if (forceCaseInsensitiveComparisons) {
9210  3148 sqlQuery = SQLConstants.GET_SUBSCRIPTION_POLICIES;
9211    }
9212   
9213  3148 try {
9214  3148 conn = APIMgtDBUtil.getConnection();
9215  3148 ps = conn.prepareStatement(sqlQuery);
9216  3148 ps.setInt(1, tenantID);
9217  3148 rs = ps.executeQuery();
9218  18882 while (rs.next()) {
9219  15734 SubscriptionPolicy subPolicy = new SubscriptionPolicy(
9220    rs.getString(ThrottlePolicyConstants.COLUMN_NAME));
9221  15734 setCommonPolicyDetails(subPolicy, rs);
9222  15734 subPolicy.setRateLimitCount(rs.getInt(ThrottlePolicyConstants.COLUMN_RATE_LIMIT_COUNT));
9223  15734 subPolicy.setRateLimitTimeUnit(rs.getString(ThrottlePolicyConstants.COLUMN_RATE_LIMIT_TIME_UNIT));
9224  15734 subPolicy.setStopOnQuotaReach(rs.getBoolean(ThrottlePolicyConstants.COLUMN_STOP_ON_QUOTA_REACH));
9225  15734 subPolicy.setBillingPlan(rs.getString(ThrottlePolicyConstants.COLUMN_BILLING_PLAN));
9226  15734 InputStream binary = rs.getBinaryStream(ThrottlePolicyConstants.COLUMN_CUSTOM_ATTRIB);
9227  15734 if (binary != null) {
9228  0 byte[] customAttrib = APIUtil.toByteArray(binary);
9229  0 subPolicy.setCustomAttributes(customAttrib);
9230    }
9231  15734 policies.add(subPolicy);
9232    }
9233    } catch (SQLException e) {
9234  0 handleException("Error while executing SQL", e);
9235    } catch (IOException e) {
9236  0 handleException("Error while converting input stream to byte array", e);
9237    } finally {
9238  3148 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
9239    }
9240  3148 return policies.toArray(new SubscriptionPolicy[policies.size()]);
9241    }
9242   
9243    /**
9244    * Get all Global level policeis belongs to specific tenant
9245    *
9246    * @param tenantID
9247    * @return
9248    * @throws APIManagementException
9249    */
 
9250  0 toggle public GlobalPolicy[] getGlobalPolicies(int tenantID) throws APIManagementException {
9251  0 List<GlobalPolicy> policies = new ArrayList<GlobalPolicy>();
9252  0 Connection conn = null;
9253  0 PreparedStatement ps = null;
9254  0 ResultSet rs = null;
9255   
9256  0 String sqlQuery = SQLConstants.GET_GLOBAL_POLICIES;
9257  0 if (forceCaseInsensitiveComparisons) {
9258  0 sqlQuery = SQLConstants.GET_GLOBAL_POLICIES;
9259    }
9260   
9261  0 try {
9262  0 conn = APIMgtDBUtil.getConnection();
9263  0 ps = conn.prepareStatement(sqlQuery);
9264  0 ps.setInt(1, tenantID);
9265  0 rs = ps.executeQuery();
9266  0 while (rs.next()) {
9267  0 String siddhiQuery = null;
9268  0 GlobalPolicy globalPolicy = new GlobalPolicy(rs.getString(ThrottlePolicyConstants.COLUMN_NAME));
9269  0 globalPolicy.setDescription(rs.getString(ThrottlePolicyConstants.COLUMN_DESCRIPTION));
9270  0 globalPolicy.setPolicyId(rs.getInt(ThrottlePolicyConstants.COLUMN_POLICY_ID));
9271  0 globalPolicy.setUUID(rs.getString(ThrottlePolicyConstants.COLUMN_UUID));
9272  0 globalPolicy.setTenantId(rs.getInt(ThrottlePolicyConstants.COLUMN_TENANT_ID));
9273  0 globalPolicy.setKeyTemplate(rs.getString(ThrottlePolicyConstants.COLUMN_KEY_TEMPLATE));
9274  0 globalPolicy.setDeployed(rs.getBoolean(ThrottlePolicyConstants.COLUMN_DEPLOYED));
9275  0 InputStream siddhiQueryBlob = rs.getBinaryStream(ThrottlePolicyConstants.COLUMN_SIDDHI_QUERY);
9276  0 if (siddhiQueryBlob != null) {
9277  0 siddhiQuery = APIMgtDBUtil.getStringFromInputStream(siddhiQueryBlob);
9278    }
9279  0 globalPolicy.setSiddhiQuery(siddhiQuery);
9280  0 policies.add(globalPolicy);
9281    }
9282    } catch (SQLException e) {
9283  0 handleException("Error while executing SQL", e);
9284    } finally {
9285  0 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
9286    }
9287  0 return policies.toArray(new GlobalPolicy[policies.size()]);
9288    }
9289   
9290   
9291    /**
9292    * Get a particular Global level policy.
9293    *
9294    * @param policyName name of the global polixy
9295    * @return {@link GlobalPolicy}
9296    * @throws APIManagementException
9297    */
 
9298  0 toggle public GlobalPolicy getGlobalPolicy(String policyName) throws APIManagementException {
9299  0 Connection conn = null;
9300  0 PreparedStatement ps = null;
9301  0 ResultSet rs = null;
9302   
9303  0 String sqlQuery = SQLConstants.GET_GLOBAL_POLICY;
9304   
9305  0 GlobalPolicy globalPolicy = null;
9306  0 try {
9307  0 conn = APIMgtDBUtil.getConnection();
9308  0 ps = conn.prepareStatement(sqlQuery);
9309  0 ps.setString(1, policyName);
9310  0 rs = ps.executeQuery();
9311   
9312  0 if (rs.next()) {
9313  0 String siddhiQuery = null;
9314  0 globalPolicy = new GlobalPolicy(rs.getString(ThrottlePolicyConstants.COLUMN_NAME));
9315  0 globalPolicy.setDescription(rs.getString(ThrottlePolicyConstants.COLUMN_DESCRIPTION));
9316  0 globalPolicy.setPolicyId(rs.getInt(ThrottlePolicyConstants.COLUMN_POLICY_ID));
9317  0 globalPolicy.setUUID(rs.getString(ThrottlePolicyConstants.COLUMN_UUID));
9318  0 globalPolicy.setTenantId(rs.getInt(ThrottlePolicyConstants.COLUMN_TENANT_ID));
9319  0 globalPolicy.setKeyTemplate(rs.getString(ThrottlePolicyConstants.COLUMN_KEY_TEMPLATE));
9320  0 globalPolicy.setDeployed(rs.getBoolean(ThrottlePolicyConstants.COLUMN_DEPLOYED));
9321  0 InputStream siddhiQueryBlob = rs.getBinaryStream(ThrottlePolicyConstants.COLUMN_SIDDHI_QUERY);
9322  0 if (siddhiQueryBlob != null) {
9323  0 siddhiQuery = APIMgtDBUtil.getStringFromInputStream(siddhiQueryBlob);
9324    }
9325  0 globalPolicy.setSiddhiQuery(siddhiQuery);
9326    }
9327    } catch (SQLException e) {
9328  0 handleException("Error while executing SQL", e);
9329    } finally {
9330  0 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
9331    }
9332  0 return globalPolicy;
9333    }
9334   
9335    /**
9336    * Get a particular Global level policy given UUID.
9337    *
9338    * @param uuid name of the global polixy
9339    * @return {@link GlobalPolicy}
9340    * @throws APIManagementException
9341    */
 
9342  0 toggle public GlobalPolicy getGlobalPolicyByUUID(String uuid) throws APIManagementException {
9343  0 Connection conn = null;
9344  0 PreparedStatement ps = null;
9345  0 ResultSet rs = null;
9346   
9347  0 String sqlQuery = SQLConstants.GET_GLOBAL_POLICY_BY_UUID;
9348   
9349  0 GlobalPolicy globalPolicy = null;
9350  0 try {
9351  0 conn = APIMgtDBUtil.getConnection();
9352  0 ps = conn.prepareStatement(sqlQuery);
9353  0 ps.setString(1, uuid);
9354  0 rs = ps.executeQuery();
9355   
9356  0 if (rs.next()) {
9357  0 String siddhiQuery = null;
9358  0 globalPolicy = new GlobalPolicy(rs.getString(ThrottlePolicyConstants.COLUMN_NAME));
9359  0 globalPolicy.setDescription(rs.getString(ThrottlePolicyConstants.COLUMN_DESCRIPTION));
9360  0 globalPolicy.setPolicyId(rs.getInt(ThrottlePolicyConstants.COLUMN_POLICY_ID));
9361  0 globalPolicy.setUUID(rs.getString(ThrottlePolicyConstants.COLUMN_UUID));
9362  0 globalPolicy.setTenantId(rs.getInt(ThrottlePolicyConstants.COLUMN_TENANT_ID));
9363  0 globalPolicy.setKeyTemplate(rs.getString(ThrottlePolicyConstants.COLUMN_KEY_TEMPLATE));
9364  0 globalPolicy.setDeployed(rs.getBoolean(ThrottlePolicyConstants.COLUMN_DEPLOYED));
9365  0 InputStream siddhiQueryBlob = rs.getBinaryStream(ThrottlePolicyConstants.COLUMN_SIDDHI_QUERY);
9366  0 if (siddhiQueryBlob != null) {
9367  0 siddhiQuery = APIMgtDBUtil.getStringFromInputStream(siddhiQueryBlob);
9368    }
9369  0 globalPolicy.setSiddhiQuery(siddhiQuery);
9370    }
9371    } catch (SQLException e) {
9372  0 handleException("Error while retrieving global policy by uuid " + uuid, e);
9373    } finally {
9374  0 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
9375    }
9376  0 return globalPolicy;
9377    }
9378   
9379    /**
9380    * Retrieves {@link APIPolicy} with name <code>policyName</code> and tenant Id <code>tenantNId</code>
9381    * <p>This will retrieve complete details about the APIPolicy with all pipelins and conditions.</p>
9382    *
9383    * @param policyName name of the policy to retrieve from the database
9384    * @param tenantId tenantId of the policy
9385    * @return {@link APIPolicy}
9386    * @throws APIManagementException
9387    */
 
9388  14 toggle public APIPolicy getAPIPolicy(String policyName, int tenantId) throws APIManagementException {
9389  14 APIPolicy policy = null;
9390  14 Connection connection = null;
9391  14 PreparedStatement selectStatement = null;
9392  14 ResultSet resultSet = null;
9393   
9394  14 String sqlQuery = SQLConstants.ThrottleSQLConstants.GET_API_POLICY_SQL;
9395  14 if (forceCaseInsensitiveComparisons) {
9396  14 sqlQuery = SQLConstants.ThrottleSQLConstants.GET_API_POLICY_SQL;
9397    }
9398   
9399  14 try {
9400  14 connection = APIMgtDBUtil.getConnection();
9401  14 selectStatement = connection.prepareStatement(sqlQuery);
9402  14 selectStatement.setString(1, policyName);
9403  14 selectStatement.setInt(2, tenantId);
9404   
9405    // Should return only single result
9406  14 resultSet = selectStatement.executeQuery();
9407  14 if (resultSet.next()) {
9408  0 policy = new APIPolicy(resultSet.getString(ThrottlePolicyConstants.COLUMN_NAME));
9409  0 setCommonPolicyDetails(policy, resultSet);
9410  0 policy.setUserLevel(resultSet.getString(ThrottlePolicyConstants.COLUMN_APPLICABLE_LEVEL));
9411  0 policy.setPipelines(getPipelines(policy.getPolicyId()));
9412    }
9413    } catch (SQLException e) {
9414  0 handleException("Failed to get api policy: " + policyName + '-' + tenantId, e);
9415    } finally {
9416  14 APIMgtDBUtil.closeAllConnections(selectStatement, connection, resultSet);
9417    }
9418  14 return policy;
9419    }
9420   
9421    /**
9422    * Retrieves {@link APIPolicy} with name <code>uuid</code>
9423    * <p>This will retrieve complete details about the APIPolicy with all pipelines and conditions.</p>
9424    *
9425    * @param uuid uuid of the policy to retrieve from the database
9426    * @return {@link APIPolicy}
9427    * @throws APIManagementException
9428    */
 
9429  0 toggle public APIPolicy getAPIPolicyByUUID(String uuid) throws APIManagementException {
9430  0 APIPolicy policy = null;
9431  0 Connection connection = null;
9432  0 PreparedStatement selectStatement = null;
9433  0 ResultSet resultSet = null;
9434   
9435  0 String sqlQuery = SQLConstants.ThrottleSQLConstants.GET_API_POLICY_BY_UUID_SQL;
9436  0 if (forceCaseInsensitiveComparisons) {
9437  0 sqlQuery = SQLConstants.ThrottleSQLConstants.GET_API_POLICY_BY_UUID_SQL;
9438    }
9439   
9440  0 try {
9441  0 connection = APIMgtDBUtil.getConnection();
9442  0 selectStatement = connection.prepareStatement(sqlQuery);
9443  0 selectStatement.setString(1, uuid);
9444   
9445    // Should return only single result
9446  0 resultSet = selectStatement.executeQuery();
9447  0 if (resultSet.next()) {
9448  0 policy = new APIPolicy(resultSet.getString(ThrottlePolicyConstants.COLUMN_NAME));
9449  0 setCommonPolicyDetails(policy, resultSet);
9450  0 policy.setUserLevel(resultSet.getString(ThrottlePolicyConstants.COLUMN_APPLICABLE_LEVEL));
9451  0 policy.setPipelines(getPipelines(policy.getPolicyId()));
9452    }
9453    } catch (SQLException e) {
9454  0 handleException("Failed to get api policy: " + uuid, e);
9455    } finally {
9456  0 APIMgtDBUtil.closeAllConnections(selectStatement, connection, resultSet);
9457    }
9458  0 return policy;
9459    }
9460   
9461    /**
9462    * Retrieves {@link ApplicationPolicy} with name <code>policyName</code> and tenant Id <code>tenantNId</code>
9463    *
9464    * @param policyName name of the policy to retrieve from the database
9465    * @param tenantId tenantId of the policy
9466    * @return {@link ApplicationPolicy}
9467    * @throws APIManagementException
9468    */
 
9469  0 toggle public ApplicationPolicy getApplicationPolicy(String policyName, int tenantId) throws APIManagementException {
9470  0 ApplicationPolicy policy = null;
9471  0 Connection connection = null;
9472  0 PreparedStatement selectStatement = null;
9473  0 ResultSet resultSet = null;
9474   
9475  0 String sqlQuery = SQLConstants.GET_APPLICATION_POLICY_SQL;
9476  0 if (forceCaseInsensitiveComparisons) {
9477  0 sqlQuery = SQLConstants.GET_APPLICATION_POLICY_SQL;
9478    }
9479   
9480  0 try {
9481  0 connection = APIMgtDBUtil.getConnection();
9482  0 selectStatement = connection.prepareStatement(sqlQuery);
9483  0 selectStatement.setString(1, policyName);
9484  0 selectStatement.setInt(2, tenantId);
9485   
9486    // Should return only single row
9487  0 resultSet = selectStatement.executeQuery();
9488  0 if (resultSet.next()) {
9489  0 policy = new ApplicationPolicy(resultSet.getString(ThrottlePolicyConstants.COLUMN_NAME));
9490  0 setCommonPolicyDetails(policy, resultSet);
9491    }
9492    } catch (SQLException e) {
9493  0 handleException("Failed to get application policy: " + policyName + '-' + tenantId, e);
9494    } finally {
9495  0 APIMgtDBUtil.closeAllConnections(selectStatement, connection, resultSet);
9496    }
9497  0 return policy;
9498    }
9499   
9500    /**
9501    * Retrieves {@link ApplicationPolicy} with name <code>uuid</code>
9502    *
9503    * @param uuid uuid of the policy to retrieve from the database
9504    * @return {@link ApplicationPolicy}
9505    * @throws APIManagementException
9506    */
 
9507  0 toggle public ApplicationPolicy getApplicationPolicyByUUID(String uuid) throws APIManagementException {
9508  0 ApplicationPolicy policy = null;
9509  0 Connection connection = null;
9510  0 PreparedStatement selectStatement = null;
9511  0 ResultSet resultSet = null;
9512   
9513  0 String sqlQuery = SQLConstants.GET_APPLICATION_POLICY_BY_UUID_SQL;
9514  0 if (forceCaseInsensitiveComparisons) {
9515  0 sqlQuery = SQLConstants.GET_APPLICATION_POLICY_BY_UUID_SQL;
9516    }
9517   
9518  0 try {
9519  0 connection = APIMgtDBUtil.getConnection();
9520  0 selectStatement = connection.prepareStatement(sqlQuery);
9521  0 selectStatement.setString(1, uuid);
9522   
9523    // Should return only single row
9524  0 resultSet = selectStatement.executeQuery();
9525  0 if (resultSet.next()) {
9526  0 policy = new ApplicationPolicy(resultSet.getString(ThrottlePolicyConstants.COLUMN_NAME));
9527  0 setCommonPolicyDetails(policy, resultSet);
9528    }
9529    } catch (SQLException e) {
9530  0 handleException("Failed to get application policy: " + uuid, e);
9531    } finally {
9532  0 APIMgtDBUtil.closeAllConnections(selectStatement, connection, resultSet);
9533    }
9534  0 return policy;
9535    }
9536   
9537    /**
9538    * Retrieves {@link SubscriptionPolicy} with name <code>policyName</code> and tenant Id <code>tenantNId</code>
9539    *
9540    * @param policyName name of the policy to retrieve from the database
9541    * @param tenantId tenantId of the policy
9542    * @return {@link SubscriptionPolicy}
9543    * @throws APIManagementException
9544    */
 
9545  0 toggle public SubscriptionPolicy getSubscriptionPolicy(String policyName, int tenantId) throws APIManagementException {
9546  0 SubscriptionPolicy policy = null;
9547  0 Connection connection = null;
9548  0 PreparedStatement selectStatement = null;
9549  0 ResultSet resultSet = null;
9550   
9551  0 String sqlQuery = SQLConstants.GET_SUBSCRIPTION_POLICY_SQL;
9552  0 if (forceCaseInsensitiveComparisons) {
9553  0 sqlQuery = SQLConstants.GET_SUBSCRIPTION_POLICY_SQL;
9554    }
9555   
9556  0 try {
9557  0 connection = APIMgtDBUtil.getConnection();
9558  0 selectStatement = connection.prepareStatement(sqlQuery);
9559  0 selectStatement.setString(1, policyName);
9560  0 selectStatement.setInt(2, tenantId);
9561   
9562    // Should return only single row
9563  0 resultSet = selectStatement.executeQuery();
9564  0 if (resultSet.next()) {
9565  0 policy = new SubscriptionPolicy(resultSet.getString(ThrottlePolicyConstants.COLUMN_NAME));
9566  0 setCommonPolicyDetails(policy, resultSet);
9567  0 policy.setRateLimitCount(resultSet.getInt(ThrottlePolicyConstants.COLUMN_RATE_LIMIT_COUNT));
9568  0 policy.setRateLimitTimeUnit(resultSet.getString(ThrottlePolicyConstants.COLUMN_RATE_LIMIT_TIME_UNIT));
9569  0 policy.setStopOnQuotaReach(resultSet.getBoolean(ThrottlePolicyConstants.COLUMN_STOP_ON_QUOTA_REACH));
9570  0 policy.setBillingPlan(resultSet.getString(ThrottlePolicyConstants.COLUMN_BILLING_PLAN));
9571  0 InputStream binary = resultSet.getBinaryStream(ThrottlePolicyConstants.COLUMN_CUSTOM_ATTRIB);
9572  0 if (binary != null) {
9573  0 byte[] customAttrib = APIUtil.toByteArray(binary);
9574  0 policy.setCustomAttributes(customAttrib);
9575    }
9576    }
9577    } catch (SQLException e) {
9578  0 handleException("Failed to get subscription policy: " + policyName + '-' + tenantId, e);
9579    } catch (IOException e) {
9580  0 handleException("Error while converting input stream to byte array", e);
9581    } finally {
9582  0 APIMgtDBUtil.closeAllConnections(selectStatement, connection, resultSet);
9583    }
9584  0 return policy;
9585    }
9586   
9587    /**
9588    * Retrieves {@link SubscriptionPolicy} with name <code>uuid</code>
9589    *
9590    * @param uuid name of the policy to retrieve from the database
9591    * @return {@link SubscriptionPolicy}
9592    * @throws APIManagementException
9593    */
 
9594  0 toggle public SubscriptionPolicy getSubscriptionPolicyByUUID(String uuid) throws APIManagementException {
9595  0 SubscriptionPolicy policy = null;
9596  0 Connection connection = null;
9597  0 PreparedStatement selectStatement = null;
9598  0 ResultSet resultSet = null;
9599   
9600  0 String sqlQuery = SQLConstants.GET_SUBSCRIPTION_POLICY_BY_UUID_SQL;
9601  0 if (forceCaseInsensitiveComparisons) {
9602  0 sqlQuery = SQLConstants.GET_SUBSCRIPTION_POLICY_BY_UUID_SQL;
9603    }
9604   
9605  0 try {
9606  0 connection = APIMgtDBUtil.getConnection();
9607  0 selectStatement = connection.prepareStatement(sqlQuery);
9608  0 selectStatement.setString(1, uuid);
9609   
9610    // Should return only single row
9611  0 resultSet = selectStatement.executeQuery();
9612  0 if (resultSet.next()) {
9613  0 policy = new SubscriptionPolicy(resultSet.getString(ThrottlePolicyConstants.COLUMN_NAME));
9614  0 setCommonPolicyDetails(policy, resultSet);
9615  0 policy.setRateLimitCount(resultSet.getInt(ThrottlePolicyConstants.COLUMN_RATE_LIMIT_COUNT));
9616  0 policy.setRateLimitTimeUnit(resultSet.getString(ThrottlePolicyConstants.COLUMN_RATE_LIMIT_TIME_UNIT));
9617  0 policy.setStopOnQuotaReach(resultSet.getBoolean(ThrottlePolicyConstants.COLUMN_STOP_ON_QUOTA_REACH));
9618  0 policy.setBillingPlan(resultSet.getString(ThrottlePolicyConstants.COLUMN_BILLING_PLAN));
9619  0 InputStream binary = resultSet.getBinaryStream(ThrottlePolicyConstants.COLUMN_CUSTOM_ATTRIB);
9620  0 if (binary != null) {
9621  0 byte[] customAttrib = APIUtil.toByteArray(binary);
9622  0 policy.setCustomAttributes(customAttrib);
9623    }
9624    }
9625    } catch (SQLException e) {
9626  0 handleException("Failed to get subscription policy: " + uuid, e);
9627    } catch (IOException e) {
9628  0 handleException("Error while converting input stream to byte array", e);
9629    } finally {
9630  0 APIMgtDBUtil.closeAllConnections(selectStatement, connection, resultSet);
9631    }
9632  0 return policy;
9633    }
9634   
9635    /**
9636    * Retrieves list of pipelines for the policy with policy Id: <code>policyId</code>
9637    *
9638    * @param policyId policy id of the pipelines
9639    * @return list of pipelines
9640    * @throws APIManagementException
9641    */
 
9642  0 toggle private ArrayList<Pipeline> getPipelines(int policyId) throws APIManagementException {
9643  0 Connection connection = null;
9644  0 PreparedStatement pipelinesStatement = null;
9645  0 ResultSet resultSet = null;
9646  0 ArrayList<Pipeline> pipelines = new ArrayList<Pipeline>();
9647   
9648  0 try {
9649  0 connection = APIMgtDBUtil.getConnection();
9650  0 pipelinesStatement = connection.prepareStatement(SQLConstants.ThrottleSQLConstants.GET_PIPELINES_SQL);
9651  0 int unitTime = 0;
9652  0 int quota = 0;
9653  0 int pipelineId = -1;
9654  0 String timeUnit = null;
9655  0 String quotaUnit = null;
9656  0 String description;
9657  0 pipelinesStatement.setInt(1, policyId);
9658  0 resultSet = pipelinesStatement.executeQuery();
9659   
9660  0 while (resultSet.next()) {
9661  0 Pipeline pipeline = new Pipeline();
9662  0 ArrayList<Condition> conditions = null;
9663  0 QuotaPolicy quotaPolicy = new QuotaPolicy();
9664  0 quotaPolicy.setType(resultSet.getString(ThrottlePolicyConstants.COLUMN_QUOTA_POLICY_TYPE));
9665  0 timeUnit = resultSet.getString(ThrottlePolicyConstants.COLUMN_TIME_UNIT);
9666  0 quotaUnit = resultSet.getString(ThrottlePolicyConstants.COLUMN_QUOTA_UNIT);
9667  0 unitTime = resultSet.getInt(ThrottlePolicyConstants.COLUMN_UNIT_TIME);
9668  0 quota = resultSet.getInt(ThrottlePolicyConstants.COLUMN_QUOTA);
9669  0 pipelineId = resultSet.getInt(ThrottlePolicyConstants.COLUMN_CONDITION_ID);
9670  0 description = resultSet.getString(ThrottlePolicyConstants.COLUMN_DESCRIPTION);
9671  0 if (PolicyConstants.REQUEST_COUNT_TYPE.equals(quotaPolicy.getType())) {
9672  0 RequestCountLimit requestCountLimit = new RequestCountLimit();
9673  0 requestCountLimit.setUnitTime(unitTime);
9674  0 requestCountLimit.setTimeUnit(timeUnit);
9675  0 requestCountLimit.setRequestCount(quota);
9676  0 quotaPolicy.setLimit(requestCountLimit);
9677  0 } else if (PolicyConstants.BANDWIDTH_TYPE.equals(quotaPolicy.getType())) {
9678  0 BandwidthLimit bandwidthLimit = new BandwidthLimit();
9679  0 bandwidthLimit.setUnitTime(unitTime);
9680  0 bandwidthLimit.setTimeUnit(timeUnit);
9681  0 bandwidthLimit.setDataUnit(quotaUnit);
9682  0 bandwidthLimit.setDataAmount(quota);
9683  0 quotaPolicy.setLimit(bandwidthLimit);
9684    }
9685   
9686  0 conditions = getConditions(pipelineId);
9687  0 pipeline.setConditions(conditions);
9688  0 pipeline.setQuotaPolicy(quotaPolicy);
9689  0 pipeline.setId(pipelineId);
9690  0 pipeline.setDescription(description);
9691  0 pipelines.add(pipeline);
9692    }
9693    } catch (SQLException e) {
9694  0 handleException("Failed to get pipelines for policyId: " + policyId, e);
9695    } finally {
9696  0 APIMgtDBUtil.closeAllConnections(pipelinesStatement, connection, resultSet);
9697    }
9698  0 return pipelines;
9699    }
9700   
9701    /**
9702    * Retrieves list of Conditions for a pipeline specified by <code>pipelineId</code>
9703    *
9704    * @param pipelineId pipeline Id with conditions to retrieve
9705    * @return list of Conditions for a pipeline
9706    * @throws APIManagementException
9707    */
 
9708  0 toggle private ArrayList<Condition> getConditions(int pipelineId) throws APIManagementException {
9709  0 Connection connection = null;
9710  0 PreparedStatement conditionsStatement = null;
9711  0 ResultSet resultSet = null;
9712  0 ArrayList<Condition> conditions = new ArrayList<Condition>();
9713  0 String startingIP = null;
9714  0 String endingIP = null;
9715  0 String specificIP = null;
9716  0 boolean invert;
9717  0 try {
9718  0 connection = APIMgtDBUtil.getConnection();
9719  0 conditionsStatement = connection.prepareStatement(SQLConstants.ThrottleSQLConstants.GET_IP_CONDITIONS_SQL);
9720  0 conditionsStatement.setInt(1, pipelineId);
9721  0 resultSet = conditionsStatement.executeQuery();
9722   
9723  0 while (resultSet.next()) {
9724  0 startingIP = resultSet.getString(ThrottlePolicyConstants.COLUMN_STARTING_IP);
9725  0 endingIP = resultSet.getString(ThrottlePolicyConstants.COLUMN_ENDING_IP);
9726  0 specificIP = resultSet.getString(ThrottlePolicyConstants.COLUMN_SPECIFIC_IP);
9727  0 invert = resultSet.getBoolean(ThrottlePolicyConstants.COLUMN_WITHIN_IP_RANGE);
9728   
9729  0 if (specificIP != null && !"".equals(specificIP)) {
9730  0 IPCondition ipCondition = new IPCondition(PolicyConstants.IP_SPECIFIC_TYPE);
9731  0 ipCondition.setSpecificIP(specificIP);
9732  0 ipCondition.setInvertCondition(invert);
9733  0 conditions.add(ipCondition);
9734  0 } else if (startingIP != null && !"".equals(startingIP)) {
9735   
9736    /*
9737    Assumes availability of starting ip means ip range is enforced.
9738    Therefore availability of ending ip is not checked.
9739    */
9740  0 IPCondition ipRangeCondition = new IPCondition(PolicyConstants.IP_RANGE_TYPE);
9741  0 ipRangeCondition.setStartingIP(startingIP);
9742  0 ipRangeCondition.setEndingIP(endingIP);
9743  0 ipRangeCondition.setInvertCondition(invert);
9744  0 conditions.add(ipRangeCondition);
9745    }
9746    }
9747  0 setHeaderConditions(pipelineId, conditions);
9748  0 setQueryParameterConditions(pipelineId, conditions);
9749  0 setJWTClaimConditions(pipelineId, conditions);
9750    } catch (SQLException e) {
9751  0 handleException("Failed to get conditions for pipelineId: " + pipelineId, e);
9752    } finally {
9753  0 APIMgtDBUtil.closeAllConnections(conditionsStatement, connection, resultSet);
9754    }
9755  0 return conditions;
9756    }
9757   
9758    /**
9759    * Add Header conditions of pipeline with pipeline Id: <code>pipelineId</code> to a
9760    * provided {@link Condition} array
9761    *
9762    * @param pipelineId Id of the pipeline
9763    * @param conditions condition array to populate
9764    * @throws APIManagementException
9765    */
 
9766  0 toggle private void setHeaderConditions(int pipelineId, ArrayList<Condition> conditions) throws APIManagementException {
9767  0 Connection connection = null;
9768  0 PreparedStatement conditionsStatement = null;
9769  0 ResultSet resultSet = null;
9770   
9771  0 try {
9772  0 connection = APIMgtDBUtil.getConnection();
9773  0 conditionsStatement = connection.prepareStatement(SQLConstants.ThrottleSQLConstants.GET_HEADER_CONDITIONS_SQL);
9774  0 conditionsStatement.setInt(1, pipelineId);
9775  0 resultSet = conditionsStatement.executeQuery();
9776   
9777  0 while (resultSet.next()) {
9778  0 HeaderCondition headerCondition = new HeaderCondition();
9779  0 headerCondition.setHeader(resultSet.getString(ThrottlePolicyConstants.COLUMN_HEADER_FIELD_NAME));
9780  0 headerCondition.setValue(resultSet.getString(ThrottlePolicyConstants.COLUMN_HEADER_FIELD_VALUE));
9781  0 headerCondition.setInvertCondition(resultSet.getBoolean(ThrottlePolicyConstants.COLUMN_IS_HEADER_FIELD_MAPPING));
9782  0 conditions.add(headerCondition);
9783    }
9784    } catch (SQLException e) {
9785  0 handleException("Failed to get header conditions for pipelineId: " + pipelineId, e);
9786    } finally {
9787  0 APIMgtDBUtil.closeAllConnections(conditionsStatement, connection, resultSet);
9788    }
9789    }
9790   
9791    /**
9792    * Add Query parameter conditions of pipeline with pipeline Id: <code>pipelineId</code> to a
9793    * provided {@link Condition} array
9794    *
9795    * @param pipelineId Id of the pipeline
9796    * @param conditions condition array to populate
9797    * @throws APIManagementException
9798    */
 
9799  0 toggle private void setQueryParameterConditions(int pipelineId, ArrayList<Condition> conditions)
9800    throws APIManagementException {
9801  0 Connection connection = null;
9802  0 PreparedStatement conditionsStatement = null;
9803  0 ResultSet resultSet = null;
9804   
9805  0 try {
9806  0 connection = APIMgtDBUtil.getConnection();
9807  0 conditionsStatement = connection.prepareStatement(SQLConstants.ThrottleSQLConstants.GET_QUERY_PARAMETER_CONDITIONS_SQL);
9808  0 conditionsStatement.setInt(1, pipelineId);
9809  0 resultSet = conditionsStatement.executeQuery();
9810   
9811  0 while (resultSet.next()) {
9812  0 QueryParameterCondition queryParameterCondition = new QueryParameterCondition();
9813  0 queryParameterCondition
9814    .setParameter(resultSet.getString(ThrottlePolicyConstants.COLUMN_PARAMETER_NAME));
9815  0 queryParameterCondition.setValue(resultSet.getString(ThrottlePolicyConstants.COLUMN_PARAMETER_VALUE));
9816  0 queryParameterCondition.setInvertCondition(resultSet.getBoolean(ThrottlePolicyConstants.COLUMN_IS_PARAM_MAPPING));
9817  0 conditions.add(queryParameterCondition);
9818    }
9819    } catch (SQLException e) {
9820  0 handleException("Failed to get query parameter conditions for pipelineId: " + pipelineId, e);
9821    } finally {
9822  0 APIMgtDBUtil.closeAllConnections(conditionsStatement, connection, resultSet);
9823    }
9824    }
9825   
9826    /**
9827    * Add JWT claim conditions of pipeline with pipeline Id: <code>pipelineId</code> to a
9828    * provided {@link Condition} array
9829    *
9830    * @param pipelineId Id of the pipeline
9831    * @param conditions condition array to populate
9832    * @throws APIManagementException
9833    */
 
9834  0 toggle private void setJWTClaimConditions(int pipelineId, ArrayList<Condition> conditions) throws APIManagementException {
9835  0 Connection connection = null;
9836  0 PreparedStatement conditionsStatement = null;
9837  0 ResultSet resultSet = null;
9838   
9839  0 try {
9840  0 connection = APIMgtDBUtil.getConnection();
9841  0 conditionsStatement = connection.prepareStatement(SQLConstants.ThrottleSQLConstants.GET_JWT_CLAIM_CONDITIONS_SQL);
9842  0 conditionsStatement.setInt(1, pipelineId);
9843  0 resultSet = conditionsStatement.executeQuery();
9844   
9845  0 while (resultSet.next()) {
9846  0 JWTClaimsCondition jwtClaimsCondition = new JWTClaimsCondition();
9847  0 jwtClaimsCondition.setClaimUrl(resultSet.getString(ThrottlePolicyConstants.COLUMN_CLAIM_URI));
9848  0 jwtClaimsCondition.setAttribute(resultSet.getString(ThrottlePolicyConstants.COLUMN_CLAIM_ATTRIBUTE));
9849  0 jwtClaimsCondition.setInvertCondition(resultSet.getBoolean(ThrottlePolicyConstants.COLUMN_IS_CLAIM_MAPPING));
9850  0 conditions.add(jwtClaimsCondition);
9851    }
9852    } catch (SQLException e) {
9853  0 handleException("Failed to get jwt claim conditions for pipelineId: " + pipelineId, e);
9854    } finally {
9855  0 APIMgtDBUtil.closeAllConnections(conditionsStatement, connection, resultSet);
9856    }
9857    }
9858   
9859    /**
9860    * Updates API level policy.
9861    * <p>policy name and tenant id should be specified in <code>policy</code></p>
9862    * <p>
9863    * Exsisting policy will be deleted and new policy will be inserted to the database
9864    * with old POLICY_ID. Uses {@link #updateAPIPolicy(APIPolicy)}
9865    * to create new policy.
9866    * </p>
9867    *
9868    * @param policy updated policy object
9869    * @throws APIManagementException
9870    */
 
9871  0 toggle public APIPolicy updateAPIPolicy(APIPolicy policy) throws APIManagementException {
9872  0 Connection connection = null;
9873  0 PreparedStatement selectStatement = null;
9874  0 PreparedStatement deleteStatement = null;
9875  0 ResultSet resultSet = null;
9876  0 int oldPolicyId = 0;
9877  0 String oldPolicyUUID = null;
9878   
9879  0 try {
9880  0 connection = APIMgtDBUtil.getConnection();
9881  0 connection.setAutoCommit(false);
9882  0 if (policy != null) {
9883  0 if (policy.getPolicyName() != null && policy.getTenantId() != -1) {
9884  0 selectStatement = connection
9885    .prepareStatement(SQLConstants.ThrottleSQLConstants.GET_API_POLICY_ID_SQL);
9886  0 selectStatement.setString(1, policy.getPolicyName());
9887  0 selectStatement.setInt(2, policy.getTenantId());
9888  0 } else if (policy.getUUID() != null) {
9889  0 selectStatement = connection
9890    .prepareStatement(SQLConstants.ThrottleSQLConstants.GET_API_POLICY_ID_BY_UUID_SQL);
9891  0 selectStatement.setString(1, policy.getUUID());
9892    } else {
9893  0 String errorMsg =
9894    "Policy object doesn't contain mandatory parameters. At least UUID or Name,Tenant Id"
9895    + " should be provided. Name: " + policy.getPolicyName()
9896    + ", Tenant Id: " + policy.getTenantId() + ", UUID: " + policy.getUUID();
9897  0 log.error(errorMsg);
9898  0 throw new APIManagementException(errorMsg);
9899    }
9900    } else {
9901  0 String errorMsg = "Provided Policy to add is null";
9902  0 log.error(errorMsg);
9903  0 throw new APIManagementException(errorMsg);
9904    }
9905   
9906    // Should return only single row
9907  0 resultSet = selectStatement.executeQuery();
9908  0 if (resultSet.next()) {
9909  0 oldPolicyId = resultSet.getInt(ThrottlePolicyConstants.COLUMN_POLICY_ID);
9910  0 oldPolicyUUID = resultSet.getString(ThrottlePolicyConstants.COLUMN_UUID);
9911    }
9912   
9913  0 deleteStatement = connection.prepareStatement(SQLConstants.ThrottleSQLConstants.DELETE_API_POLICY_SQL);
9914  0 deleteStatement.setInt(1, policy.getTenantId());
9915  0 deleteStatement.setString(2, policy.getPolicyName());
9916  0 deleteStatement.executeUpdate();
9917  0 policy.setPolicyId(oldPolicyId);
9918  0 if (!StringUtils.isBlank(oldPolicyUUID)) {
9919  0 policy.setUUID(oldPolicyUUID);
9920    }
9921  0 updateAPIPolicy(policy, connection);
9922  0 connection.commit();
9923    } catch (SQLException e) {
9924  0 if (connection != null) {
9925  0 try {
9926  0 connection.rollback();
9927    } catch (SQLException ex) {
9928   
9929    // Rollback failed. Exception will be thrown later for upper exception
9930  0 log.error("Failed to rollback the add Api Policy: " + policy.toString(), ex);
9931    }
9932    }
9933  0 handleException("Failed to update api policy: " + policy.getPolicyName() + '-' + policy.getTenantId(), e);
9934    } finally {
9935  0 APIMgtDBUtil.closeAllConnections(selectStatement, connection, resultSet);
9936  0 APIMgtDBUtil.closeAllConnections(deleteStatement, null, null);
9937    }
9938  0 return policy;
9939    }
9940   
9941    /**
9942    * Updates Application level policy.
9943    * <p>policy name and tenant id should be specified in <code>policy</code></p>
9944    *
9945    * @param policy updated policy object
9946    * @throws APIManagementException
9947    */
 
9948  0 toggle public void updateApplicationPolicy(ApplicationPolicy policy) throws APIManagementException {
9949  0 Connection connection = null;
9950  0 PreparedStatement updateStatement = null;
9951  0 boolean hasCustomAttrib = false;
9952  0 String updateQuery;
9953   
9954  0 if (policy.getTenantId() == -1 || StringUtils.isEmpty(policy.getPolicyName())) {
9955  0 String errorMsg = "Policy object doesn't contain mandatory parameters. Name: " + policy.getPolicyName() +
9956    ", Tenant Id: " + policy.getTenantId();
9957  0 log.error(errorMsg);
9958  0 throw new APIManagementException(errorMsg);
9959    }
9960   
9961  0 try {
9962  0 if (policy.getCustomAttributes() != null) {
9963  0 hasCustomAttrib = true;
9964    }
9965  0 connection = APIMgtDBUtil.getConnection();
9966  0 connection.setAutoCommit(false);
9967  0 if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
9968  0 updateQuery = SQLConstants.UPDATE_APPLICATION_POLICY_SQL;
9969  0 if (hasCustomAttrib) {
9970  0 updateQuery = SQLConstants.UPDATE_APPLICATION_POLICY_WITH_CUSTOM_ATTRIBUTES_SQL;
9971    }
9972  0 } else if (!StringUtils.isBlank(policy.getUUID())) {
9973  0 updateQuery = SQLConstants.UPDATE_APPLICATION_POLICY_BY_UUID_SQL;
9974  0 if (hasCustomAttrib) {
9975  0 updateQuery = SQLConstants.UPDATE_APPLICATION_POLICY_WITH_CUSTOM_ATTRIBUTES_BY_UUID_SQL;
9976    }
9977    } else {
9978  0 String errorMsg =
9979    "Policy object doesn't contain mandatory parameters. At least UUID or Name,Tenant Id"
9980    + " should be provided. Name: " + policy.getPolicyName()
9981    + ", Tenant Id: " + policy.getTenantId() + ", UUID: " + policy.getUUID();
9982  0 log.error(errorMsg);
9983  0 throw new APIManagementException(errorMsg);
9984    }
9985   
9986  0 updateStatement = connection.prepareStatement(updateQuery);
9987  0 if (!StringUtils.isEmpty(policy.getDisplayName())) {
9988  0 updateStatement.setString(1, policy.getDisplayName());
9989    } else {
9990  0 updateStatement.setString(1, policy.getPolicyName());
9991    }
9992  0 updateStatement.setString(2, policy.getDescription());
9993  0 updateStatement.setString(3, policy.getDefaultQuotaPolicy().getType());
9994   
9995  0 if (PolicyConstants.REQUEST_COUNT_TYPE.equalsIgnoreCase(policy.getDefaultQuotaPolicy().getType())) {
9996  0 RequestCountLimit limit = (RequestCountLimit) policy.getDefaultQuotaPolicy().getLimit();
9997  0 updateStatement.setLong(4, limit.getRequestCount());
9998  0 updateStatement.setString(5, null);
9999  0 } else if (PolicyConstants.BANDWIDTH_TYPE.equalsIgnoreCase(policy.getDefaultQuotaPolicy().getType())) {
10000  0 BandwidthLimit limit = (BandwidthLimit) policy.getDefaultQuotaPolicy().getLimit();
10001  0 updateStatement.setLong(4, limit.getDataAmount());
10002  0 updateStatement.setString(5, limit.getDataUnit());
10003    }
10004  0 updateStatement.setLong(6, policy.getDefaultQuotaPolicy().getLimit().getUnitTime());
10005  0 updateStatement.setString(7, policy.getDefaultQuotaPolicy().getLimit().getTimeUnit());
10006   
10007  0 if (hasCustomAttrib) {
10008  0 updateStatement.setBlob(8, new ByteArrayInputStream(policy.getCustomAttributes()));
10009  0 if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
10010  0 updateStatement.setString(9, policy.getPolicyName());
10011  0 updateStatement.setInt(10, policy.getTenantId());
10012  0 } else if (!StringUtils.isBlank(policy.getUUID())) {
10013  0 updateStatement.setString(9, policy.getUUID());
10014    }
10015    } else {
10016  0 if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
10017  0 updateStatement.setString(8, policy.getPolicyName());
10018  0 updateStatement.setInt(9, policy.getTenantId());
10019  0 } else if (!StringUtils.isBlank(policy.getUUID())) {
10020  0 updateStatement.setString(8, policy.getUUID());
10021    }
10022    }
10023  0 updateStatement.executeUpdate();
10024  0 connection.commit();
10025    } catch (SQLException e) {
10026  0 if (connection != null) {
10027  0 try {
10028  0 connection.rollback();
10029    } catch (SQLException ex) {
10030   
10031    // Rollback failed. Exception will be thrown later for upper exception
10032  0 log.error("Failed to rollback the update Application Policy: " + policy.toString(), ex);
10033    }
10034    }
10035  0 handleException(
10036    "Failed to update application policy: " + policy.getPolicyName() + '-' + policy.getTenantId(), e);
10037    } finally {
10038  0 APIMgtDBUtil.closeAllConnections(updateStatement, connection, null);
10039    }
10040    }
10041   
10042    /**
10043    * Updates Subscription level policy.
10044    * <p>policy name and tenant id should be specified in <code>policy</code></p>
10045    *
10046    * @param policy updated policy object
10047    * @throws APIManagementException
10048    */
 
10049  0 toggle public void updateSubscriptionPolicy(SubscriptionPolicy policy) throws APIManagementException {
10050  0 Connection connection = null;
10051  0 PreparedStatement updateStatement = null;
10052  0 boolean hasCustomAttrib = false;
10053  0 String updateQuery;
10054   
10055  0 try {
10056  0 if (policy.getCustomAttributes() != null) {
10057  0 hasCustomAttrib = true;
10058    }
10059  0 if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
10060  0 updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_POLICY_SQL;
10061  0 if (hasCustomAttrib) {
10062  0 updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_POLICY_WITH_CUSTOM_ATTRIBUTES_SQL;
10063    }
10064  0 } else if (!StringUtils.isBlank(policy.getUUID())) {
10065  0 updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_POLICY_BY_UUID_SQL;
10066  0 if (hasCustomAttrib) {
10067  0 updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_POLICY_WITH_CUSTOM_ATTRIBUTES_BY_UUID_SQL;
10068    }
10069    } else {
10070  0 String errorMsg =
10071    "Policy object doesn't contain mandatory parameters. At least UUID or Name,Tenant Id"
10072    + " should be provided. Name: " + policy.getPolicyName()
10073    + ", Tenant Id: " + policy.getTenantId() + ", UUID: " + policy.getUUID();
10074  0 log.error(errorMsg);
10075  0 throw new APIManagementException(errorMsg);
10076    }
10077   
10078  0 connection = APIMgtDBUtil.getConnection();
10079  0 connection.setAutoCommit(false);
10080  0 updateStatement = connection.prepareStatement(updateQuery);
10081  0 if (!StringUtils.isEmpty(policy.getDisplayName())) {
10082  0 updateStatement.setString(1, policy.getDisplayName());
10083    } else {
10084  0 updateStatement.setString(1, policy.getPolicyName());
10085    }
10086  0 updateStatement.setString(2, policy.getDescription());
10087  0 updateStatement.setString(3, policy.getDefaultQuotaPolicy().getType());
10088   
10089  0 if (PolicyConstants.REQUEST_COUNT_TYPE.equalsIgnoreCase(policy.getDefaultQuotaPolicy().getType())) {
10090  0 RequestCountLimit limit = (RequestCountLimit) policy.getDefaultQuotaPolicy().getLimit();
10091  0 updateStatement.setLong(4, limit.getRequestCount());
10092  0 updateStatement.setString(5, null);
10093  0 } else if (PolicyConstants.BANDWIDTH_TYPE.equalsIgnoreCase(policy.getDefaultQuotaPolicy().getType())) {
10094  0 BandwidthLimit limit = (BandwidthLimit) policy.getDefaultQuotaPolicy().getLimit();
10095  0 updateStatement.setLong(4, limit.getDataAmount());
10096  0 updateStatement.setString(5, limit.getDataUnit());
10097    }
10098   
10099  0 updateStatement.setLong(6, policy.getDefaultQuotaPolicy().getLimit().getUnitTime());
10100  0 updateStatement.setString(7, policy.getDefaultQuotaPolicy().getLimit().getTimeUnit());
10101  0 updateStatement.setInt(8, policy.getRateLimitCount());
10102  0 updateStatement.setString(9, policy.getRateLimitTimeUnit());
10103  0 updateStatement.setBoolean(10, policy.isStopOnQuotaReach());
10104  0 updateStatement.setString(11, policy.getBillingPlan());
10105   
10106  0 if (hasCustomAttrib) {
10107  0 long lengthOfStream = policy.getCustomAttributes().length;
10108  0 updateStatement.setBinaryStream(12, new ByteArrayInputStream(policy.getCustomAttributes()),
10109    lengthOfStream);
10110  0 if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
10111  0 updateStatement.setString(13, policy.getPolicyName());
10112  0 updateStatement.setInt(14, policy.getTenantId());
10113  0 } else if (!StringUtils.isBlank(policy.getUUID())) {
10114  0 updateStatement.setString(13, policy.getUUID());
10115    }
10116    } else {
10117  0 if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
10118  0 updateStatement.setString(12, policy.getPolicyName());
10119  0 updateStatement.setInt(13, policy.getTenantId());
10120  0 } else if (!StringUtils.isBlank(policy.getUUID())) {
10121  0 updateStatement.setString(12, policy.getUUID());
10122    }
10123    }
10124  0 updateStatement.executeUpdate();
10125  0 connection.commit();
10126    } catch (SQLException e) {
10127  0 if (connection != null) {
10128  0 try {
10129  0 connection.rollback();
10130    } catch (SQLException ex) {
10131   
10132    // Rollback failed. Exception will be thrown later for upper exception
10133  0 log.error("Failed to rollback the update Subscription Policy: " + policy.toString(), ex);
10134    }
10135    }
10136  0 handleException(
10137    "Failed to update subscription policy: " + policy.getPolicyName() + '-' + policy.getTenantId(), e);
10138    } finally {
10139  0 APIMgtDBUtil.closeAllConnections(updateStatement, connection, null);
10140    }
10141    }
10142   
10143    /**
10144    * Updates global throttle policy in database
10145    *
10146    * @param policy updated policy obejct
10147    * @throws APIManagementException
10148    */
 
10149  0 toggle public void updateGlobalPolicy(GlobalPolicy policy) throws APIManagementException {
10150  0 Connection connection = null;
10151  0 PreparedStatement updateStatement = null;
10152  0 InputStream siddhiQueryInputStream;
10153   
10154  0 try {
10155  0 byte[] byteArray = policy.getSiddhiQuery().getBytes(Charset.defaultCharset());
10156  0 int lengthOfBytes = byteArray.length;
10157  0 siddhiQueryInputStream = new ByteArrayInputStream(byteArray);
10158  0 connection = APIMgtDBUtil.getConnection();
10159  0 connection.setAutoCommit(false);
10160  0 if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
10161  0 updateStatement = connection.prepareStatement(SQLConstants.UPDATE_GLOBAL_POLICY_SQL);
10162  0 } else if (!StringUtils.isBlank(policy.getUUID())) {
10163  0 updateStatement = connection.prepareStatement(SQLConstants.UPDATE_GLOBAL_POLICY_BY_UUID_SQL);
10164    } else {
10165  0 String errorMsg =
10166    "Policy object doesn't contain mandatory parameters. At least UUID or Name,Tenant Id"
10167    + " should be provided. Name: " + policy.getPolicyName()
10168    + ", Tenant Id: " + policy.getTenantId() + ", UUID: " + policy.getUUID();
10169  0 log.error(errorMsg);
10170  0 throw new APIManagementException(errorMsg);
10171    }
10172   
10173  0 updateStatement.setString(1, policy.getDescription());
10174  0 updateStatement.setBinaryStream(2, siddhiQueryInputStream, lengthOfBytes);
10175  0 updateStatement.setString(3, policy.getKeyTemplate());
10176  0 if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
10177  0 updateStatement.setString(4, policy.getPolicyName());
10178  0 updateStatement.setInt(5, policy.getTenantId());
10179  0 } else if (!StringUtils.isBlank(policy.getUUID())) {
10180  0 updateStatement.setString(4, policy.getUUID());
10181    }
10182  0 updateStatement.executeUpdate();
10183  0 connection.commit();
10184    } catch (SQLException e) {
10185  0 if (connection != null) {
10186  0 try {
10187  0 connection.rollback();
10188    } catch (SQLException ex) {
10189   
10190    // Rollback failed. Exception will be thrown later for upper exception
10191  0 log.error("Failed to rollback the update Global Policy: " + policy.toString(), ex);
10192    }
10193    }
10194  0 handleException("Failed to update global policy: " + policy.getPolicyName() + '-' + policy.getTenantId(),
10195    e);
10196    } finally {
10197  0 APIMgtDBUtil.closeAllConnections(updateStatement, connection, null);
10198    }
10199    }
10200   
10201    /**
10202    * Retrieves list of available policy names under <code>policyLevel</code>
10203    * and user <code>username</code>'s tenant
10204    *
10205    * @param policyLevel policY level to filter policies
10206    * @param username username will be used to get the tenant
10207    * @return array of policy names
10208    * @throws APIManagementException
10209    */
 
10210  607 toggle public String[] getPolicyNames(String policyLevel, String username) throws APIManagementException {
10211   
10212  607 List<String> names = new ArrayList<String>();
10213  607 Connection conn = null;
10214  607 PreparedStatement ps = null;
10215  607 ResultSet rs = null;
10216  607 String sqlQuery = null;
10217   
10218  607 int tenantID = APIUtil.getTenantId(username);
10219   
10220  607 try {
10221  607 conn = APIMgtDBUtil.getConnection();
10222  607 if (PolicyConstants.POLICY_LEVEL_API.equals(policyLevel)) {
10223  0 sqlQuery = SQLConstants.ThrottleSQLConstants.GET_API_POLICY_NAMES;
10224  607 } else if (PolicyConstants.POLICY_LEVEL_APP.equals(policyLevel)) {
10225  0 sqlQuery = SQLConstants.GET_APP_POLICY_NAMES;
10226  607 } else if (PolicyConstants.POLICY_LEVEL_SUB.equals(policyLevel)) {
10227  607 sqlQuery = SQLConstants.GET_SUB_POLICY_NAMES;
10228  0 } else if (PolicyConstants.POLICY_LEVEL_GLOBAL.equals(policyLevel)) {
10229  0 sqlQuery = SQLConstants.GET_GLOBAL_POLICY_NAMES;
10230    }
10231  607 ps = conn.prepareStatement(sqlQuery);
10232  607 ps.setInt(1, tenantID);
10233  607 rs = ps.executeQuery();
10234  3642 while (rs.next()) {
10235  3035 names.add(rs.getString(ThrottlePolicyConstants.COLUMN_NAME));
10236    }
10237   
10238    } catch (SQLException e) {
10239  0 handleException("Error while executing SQL", e);
10240    } finally {
10241  607 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
10242    }
10243  607 return names.toArray(new String[names.size()]);
10244    }
10245   
10246    /**
10247    * Sets deployment status vaule of a policy in database.
10248    *
10249    * @param policyLevel policy level
10250    * @param policyName name of the policy
10251    * @param tenantId tenant id of the policy
10252    * @param isDeployed deployment status. <code>true</code> if deployment successful, <code>false</code> if not
10253    * @throws APIManagementException
10254    */
 
10255  67 toggle public void setPolicyDeploymentStatus(String policyLevel, String policyName, int tenantId, boolean isDeployed)
10256    throws APIManagementException {
10257  67 Connection connection = null;
10258  67 PreparedStatement statusStatement = null;
10259  67 String query = null;
10260   
10261  67 if (PolicyConstants.POLICY_LEVEL_APP.equals(policyLevel)) {
10262  20 query = SQLConstants.UPDATE_APPLICATION_POLICY_STATUS_SQL;
10263  47 } else if (PolicyConstants.POLICY_LEVEL_SUB.equals(policyLevel)) {
10264  25 query = SQLConstants.UPDATE_SUBSCRIPTION_POLICY_STATUS_SQL;
10265  22 } else if (PolicyConstants.POLICY_LEVEL_API.equals(policyLevel)) {
10266  22 query = SQLConstants.ThrottleSQLConstants.UPDATE_API_POLICY_STATUS_SQL;
10267  0 } else if (PolicyConstants.POLICY_LEVEL_GLOBAL.equals(policyLevel)) {
10268  0 query = SQLConstants.UPDATE_GLOBAL_POLICY_STATUS_SQL;
10269    }
10270   
10271  67 try {
10272  67 connection = APIMgtDBUtil.getConnection();
10273  67 connection.setAutoCommit(false);
10274  67 statusStatement = connection.prepareStatement(query);
10275  67 statusStatement.setBoolean(1, isDeployed);
10276  67 statusStatement.setString(2, policyName);
10277  67 statusStatement.setInt(3, tenantId);
10278  67 statusStatement.executeUpdate();
10279   
10280  67 connection.commit();
10281    } catch (SQLException e) {
10282  0 if (connection != null) {
10283  0 try {
10284  0 connection.rollback();
10285    } catch (SQLException ex) {
10286   
10287    // Rollback failed. Exception will be thrown later for upper exception
10288  0 log.error("Failed to rollback setting isDeployed flag: " + policyName + '-' + tenantId, ex);
10289    }
10290    }
10291  0 handleException("Failed to set deployment status to the policy: " + policyName + '-' + tenantId, e);
10292    } finally {
10293  67 APIMgtDBUtil.closeAllConnections(statusStatement, connection, null);
10294    }
10295    }
10296   
10297    /**
10298    * Populates common attribute data of the <code>policy</code> to <code>policyStatement</code>
10299    *
10300    * @param policyStatement prepared statement initialized of policy operation
10301    * @param policy <code>Policy</code> object with data
10302    * @throws SQLException
10303    */
 
10304  67 toggle private void setCommonParametersForPolicy(PreparedStatement policyStatement, Policy policy) throws SQLException {
10305  67 policyStatement.setString(1, policy.getPolicyName());
10306  67 if (!StringUtils.isEmpty(policy.getDisplayName())) {
10307  65 policyStatement.setString(2, policy.getDisplayName());
10308    } else {
10309  2 policyStatement.setString(2, policy.getPolicyName());
10310    }
10311  67 policyStatement.setInt(3, policy.getTenantId());
10312  67 policyStatement.setString(4, policy.getDescription());
10313  67 policyStatement.setString(5, policy.getDefaultQuotaPolicy().getType());
10314   
10315    //TODO use requestCount in same format in all places
10316  67 if (PolicyConstants.REQUEST_COUNT_TYPE.equalsIgnoreCase(policy.getDefaultQuotaPolicy().getType())) {
10317  67 RequestCountLimit limit = (RequestCountLimit) policy.getDefaultQuotaPolicy().getLimit();
10318  67 policyStatement.setLong(6, limit.getRequestCount());
10319  67 policyStatement.setString(7, null);
10320  0 } else if (PolicyConstants.BANDWIDTH_TYPE.equalsIgnoreCase(policy.getDefaultQuotaPolicy().getType())) {
10321  0 BandwidthLimit limit = (BandwidthLimit) policy.getDefaultQuotaPolicy().getLimit();
10322  0 policyStatement.setLong(6, limit.getDataAmount());
10323  0 policyStatement.setString(7, limit.getDataUnit());
10324    }
10325   
10326  67 policyStatement.setLong(8, policy.getDefaultQuotaPolicy().getLimit().getUnitTime());
10327  67 policyStatement.setString(9, policy.getDefaultQuotaPolicy().getLimit().getTimeUnit());
10328    //policyStatement.setBoolean(9, APIUtil.isContentAwarePolicy(policy));
10329  67 policyStatement.setBoolean(10, policy.isDeployed());
10330  67 if (!StringUtils.isBlank(policy.getUUID())) {
10331  0 policyStatement.setString(11, policy.getUUID());
10332    } else {
10333  67 policyStatement.setString(11, UUID.randomUUID().toString());
10334    }
10335    }
10336   
10337    /**
10338    * Populated common attributes of policy type objects to <code>policy</code>
10339    * from <code>resultSet</code>
10340    *
10341    * @param policy initiallized {@link Policy} object to populate
10342    * @param resultSet {@link ResultSet} with data to populate <code>policy</code>
10343    * @throws SQLException
10344    */
 
10345  16282 toggle private void setCommonPolicyDetails(Policy policy, ResultSet resultSet) throws SQLException {
10346  16282 QuotaPolicy quotaPolicy = new QuotaPolicy();
10347  16282 String prefix = "";
10348   
10349  16282 if (policy instanceof APIPolicy) {
10350  0 prefix = "DEFAULT_";
10351    }
10352   
10353  16282 quotaPolicy.setType(resultSet.getString(prefix + ThrottlePolicyConstants.COLUMN_QUOTA_POLICY_TYPE));
10354  16282 if (resultSet.getString(prefix + ThrottlePolicyConstants.COLUMN_QUOTA_POLICY_TYPE)
10355    .equalsIgnoreCase(PolicyConstants.REQUEST_COUNT_TYPE)) {
10356  16282 RequestCountLimit reqLimit = new RequestCountLimit();
10357  16282 reqLimit.setUnitTime(resultSet.getInt(prefix + ThrottlePolicyConstants.COLUMN_UNIT_TIME));
10358  16282 reqLimit.setTimeUnit(resultSet.getString(prefix + ThrottlePolicyConstants.COLUMN_TIME_UNIT));
10359  16282 reqLimit.setRequestCount(resultSet.getInt(prefix + ThrottlePolicyConstants.COLUMN_QUOTA));
10360  16282 quotaPolicy.setLimit(reqLimit);
10361  0 } else if (resultSet.getString(prefix + ThrottlePolicyConstants.COLUMN_QUOTA_POLICY_TYPE)
10362    .equalsIgnoreCase(PolicyConstants.BANDWIDTH_TYPE)) {
10363  0 BandwidthLimit bandLimit = new BandwidthLimit();
10364  0 bandLimit.setUnitTime(resultSet.getInt(prefix + ThrottlePolicyConstants.COLUMN_UNIT_TIME));
10365  0 bandLimit.setTimeUnit(resultSet.getString(prefix + ThrottlePolicyConstants.COLUMN_TIME_UNIT));
10366  0 bandLimit.setDataAmount(resultSet.getInt(prefix + ThrottlePolicyConstants.COLUMN_QUOTA));
10367  0 bandLimit.setDataUnit(resultSet.getString(prefix + ThrottlePolicyConstants.COLUMN_QUOTA_UNIT));
10368  0 quotaPolicy.setLimit(bandLimit);
10369    }
10370   
10371  16282 policy.setUUID(resultSet.getString(ThrottlePolicyConstants.COLUMN_UUID));
10372  16282 policy.setDescription(resultSet.getString(ThrottlePolicyConstants.COLUMN_DESCRIPTION));
10373  16282 policy.setDisplayName(resultSet.getString(ThrottlePolicyConstants.COLUMN_DISPLAY_NAME));
10374  16282 policy.setPolicyId(resultSet.getInt(ThrottlePolicyConstants.COLUMN_POLICY_ID));
10375  16282 policy.setTenantId(resultSet.getInt(ThrottlePolicyConstants.COLUMN_TENANT_ID));
10376  16282 policy.setTenantDomain(IdentityTenantUtil.getTenantDomain(policy.getTenantId()));
10377  16282 policy.setDefaultQuotaPolicy(quotaPolicy);
10378  16282 policy.setDeployed(resultSet.getBoolean(ThrottlePolicyConstants.COLUMN_DEPLOYED));
10379    }
10380   
 
10381  98 toggle public boolean isPolicyExist(String policyType, int tenantId, String policyName) throws APIManagementException {
10382  98 Connection connection = null;
10383  98 PreparedStatement isExistStatement = null;
10384   
10385  98 boolean isExist = false;
10386  98 String policyTable = null;
10387  98 if (PolicyConstants.POLICY_LEVEL_API.equalsIgnoreCase(policyType)) {
10388  20 policyTable = PolicyConstants.API_THROTTLE_POLICY_TABLE;
10389  78 } else if (PolicyConstants.POLICY_LEVEL_APP.equalsIgnoreCase(policyType)) {
10390  53 policyTable = PolicyConstants.POLICY_APPLICATION_TABLE;
10391  25 } else if (PolicyConstants.POLICY_LEVEL_GLOBAL.equalsIgnoreCase(policyType)) {
10392  0 policyTable = PolicyConstants.POLICY_GLOBAL_TABLE;
10393  25 } else if (PolicyConstants.POLICY_LEVEL_SUB.equalsIgnoreCase(policyType)) {
10394  25 policyTable = PolicyConstants.POLICY_SUBSCRIPTION_TABLE;
10395    }
10396  98 try {
10397  98 String query = "SELECT " + PolicyConstants.POLICY_ID + " FROM " + policyTable + " WHERE TENANT_ID =? AND NAME = ? ";
10398  98 connection = APIMgtDBUtil.getConnection();
10399  98 connection.setAutoCommit(true);
10400  98 isExistStatement = connection.prepareStatement(query);
10401  98 isExistStatement.setInt(1, tenantId);
10402  98 isExistStatement.setString(2, policyName);
10403  98 ResultSet result = isExistStatement.executeQuery();
10404  98 if (result != null && result.next()) {
10405  28 isExist = true;
10406    }
10407    } catch (SQLException e) {
10408  0 handleException("Failed to check is exist: " + policyName + '-' + tenantId, e);
10409    } finally {
10410  98 APIMgtDBUtil.closeAllConnections(isExistStatement, connection, null);
10411    }
10412  98 return isExist;
10413    }
10414   
 
10415  65 toggle public boolean isPolicyDeployed(String policyType, int tenantId, String policyName) throws APIManagementException {
10416  65 Connection connection = null;
10417  65 PreparedStatement isExistStatement = null;
10418   
10419  65 boolean isDeployed = false;
10420  65 String policyTable = null;
10421  65 if (PolicyConstants.POLICY_LEVEL_API.equalsIgnoreCase(policyType)) {
10422  20 policyTable = PolicyConstants.API_THROTTLE_POLICY_TABLE;
10423  45 } else if (PolicyConstants.POLICY_LEVEL_APP.equalsIgnoreCase(policyType)) {
10424  20 policyTable = PolicyConstants.POLICY_APPLICATION_TABLE;
10425  25 } else if (PolicyConstants.POLICY_LEVEL_GLOBAL.equalsIgnoreCase(policyType)) {
10426  0 policyTable = PolicyConstants.POLICY_GLOBAL_TABLE;
10427  25 } else if (PolicyConstants.POLICY_LEVEL_SUB.equalsIgnoreCase(policyType)) {
10428  25 policyTable = PolicyConstants.POLICY_SUBSCRIPTION_TABLE;
10429    }
10430  65 try {
10431  65 String query = "SELECT " + PolicyConstants.POLICY_IS_DEPLOYED + " FROM " + policyTable + " WHERE TENANT_ID =? AND NAME = ? ";
10432  65 connection = APIMgtDBUtil.getConnection();
10433  65 connection.setAutoCommit(true);
10434  65 isExistStatement = connection.prepareStatement(query);
10435  65 isExistStatement.setInt(1, tenantId);
10436  65 isExistStatement.setString(2, policyName);
10437  65 ResultSet result = isExistStatement.executeQuery();
10438  65 if (result != null && result.next()) {
10439  65 isDeployed = result.getBoolean(PolicyConstants.POLICY_IS_DEPLOYED);
10440    }
10441    } catch (SQLException e) {
10442  0 handleException("Failed to check is exist: " + policyName + '-' + tenantId, e);
10443    } finally {
10444  65 APIMgtDBUtil.closeAllConnections(isExistStatement, connection, null);
10445    }
10446  65 return isDeployed;
10447    }
10448   
10449    /**
10450    * Add a block condition
10451    *
10452    * @param conditionType Type of the block condition
10453    * @param conditionValue value related to the type
10454    * @param tenantDomain tenant domain the block condition should be effective
10455    * @return uuid of the block condition if successfully added
10456    * @throws APIManagementException
10457    */
 
10458  0 toggle public String addBlockConditions(String conditionType, String conditionValue, String tenantDomain) throws
10459    APIManagementException {
10460  0 Connection connection = null;
10461  0 PreparedStatement insertPreparedStatement = null;
10462  0 boolean status = false;
10463  0 boolean valid = false;
10464  0 ResultSet rs = null;
10465  0 String uuid = null;
10466  0 try {
10467  0 String query = SQLConstants.ThrottleSQLConstants.ADD_BLOCK_CONDITIONS_SQL;
10468  0 if (APIConstants.BLOCKING_CONDITIONS_API.equals(conditionType)) {
10469  0 String extractedTenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(conditionValue);
10470  0 if (extractedTenantDomain == null) {
10471  0 extractedTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
10472    }
10473  0 if (tenantDomain.equals(extractedTenantDomain) && isValidContext(conditionValue)) {
10474  0 valid = true;
10475    } else {
10476  0 throw new APIManagementException("Couldn't Save Block Condition Due to Invalid API Context " +
10477    conditionValue);
10478    }
10479  0 } else if (APIConstants.BLOCKING_CONDITIONS_APPLICATION.equals(conditionType)) {
10480  0 String appArray[] = conditionValue.split(":");
10481  0 if (appArray.length > 1) {
10482  0 String appOwner = appArray[0];
10483  0 String appName = appArray[1];
10484   
10485  0 if ((MultitenantUtils.getTenantDomain(appOwner).equals(tenantDomain)) &&
10486    isValidApplication(appOwner, appName)) {
10487  0 valid = true;
10488    } else {
10489  0 throw new APIManagementException("Couldn't Save Block Condition Due to Invalid Application " +
10490    "name " + appName + " from Application " +
10491    "Owner " + appOwner);
10492    }
10493    }
10494  0 } else if (APIConstants.BLOCKING_CONDITIONS_USER.equals(conditionType)) {
10495  0 if (MultitenantUtils.getTenantDomain(conditionValue).equals(tenantDomain)) {
10496  0 valid = true;
10497    } else {
10498  0 throw new APIManagementException("Invalid User in Tenant Domain " + tenantDomain);
10499    }
10500  0 } else if (APIConstants.BLOCKING_CONDITIONS_IP.equals(conditionType)) {
10501  0 valid = true;
10502    }
10503  0 if (valid) {
10504  0 connection = APIMgtDBUtil.getConnection();
10505  0 connection.setAutoCommit(false);
10506  0 if (!isBlockConditionExist(conditionType, conditionValue, tenantDomain, connection)) {
10507  0 uuid = UUID.randomUUID().toString();
10508  0 insertPreparedStatement = connection.prepareStatement(query);
10509  0 insertPreparedStatement.setString(1, conditionType);
10510  0 insertPreparedStatement.setString(2, conditionValue);
10511  0 insertPreparedStatement.setString(3, "TRUE");
10512  0 insertPreparedStatement.setString(4, tenantDomain);
10513  0 insertPreparedStatement.setString(5, uuid);
10514  0 status = insertPreparedStatement.execute();
10515  0 connection.commit();
10516  0 status = true;
10517    } else {
10518  0 throw new BlockConditionAlreadyExistsException(
10519    "Condition with type: " + conditionType + ", value: " + conditionValue + " already exists");
10520    }
10521    }
10522    } catch (SQLException e) {
10523  0 if (connection != null) {
10524  0 try {
10525  0 connection.rollback();
10526    } catch (SQLException ex) {
10527  0 handleException(
10528    "Failed to rollback adding Block condition : " + conditionType + " and " + conditionValue,
10529    ex);
10530    }
10531    }
10532  0 handleException("Failed to add Block condition : " + conditionType + " and " + conditionValue, e);
10533    } finally {
10534  0 APIMgtDBUtil.closeAllConnections(insertPreparedStatement, connection, null);
10535    }
10536  0 if (status) {
10537  0 return uuid;
10538    } else {
10539  0 return null;
10540    }
10541    }
10542   
10543    /**
10544    * Get details of a block condition by Id
10545    *
10546    * @param conditionId id of the condition
10547    * @return Block conditoin represented by the UUID
10548    * @throws APIManagementException
10549    */
 
10550  0 toggle public BlockConditionsDTO getBlockCondition(int conditionId) throws APIManagementException {
10551  0 Connection connection = null;
10552  0 PreparedStatement selectPreparedStatement = null;
10553  0 ResultSet resultSet = null;
10554  0 BlockConditionsDTO blockCondition = null;
10555  0 try {
10556  0 String query = SQLConstants.ThrottleSQLConstants.GET_BLOCK_CONDITION_SQL;
10557  0 connection = APIMgtDBUtil.getConnection();
10558  0 connection.setAutoCommit(true);
10559  0 selectPreparedStatement = connection.prepareStatement(query);
10560  0 selectPreparedStatement.setInt(1, conditionId);
10561  0 resultSet = selectPreparedStatement.executeQuery();
10562  0 if (resultSet.next()) {
10563  0 blockCondition = new BlockConditionsDTO();
10564  0 blockCondition.setEnabled(resultSet.getBoolean("ENABLED"));
10565  0 blockCondition.setConditionType(resultSet.getString("TYPE"));
10566  0 blockCondition.setConditionValue(resultSet.getString("VALUE"));
10567  0 blockCondition.setConditionId(conditionId);
10568  0 blockCondition.setTenantDomain(resultSet.getString("DOMAIN"));
10569  0 blockCondition.setUUID(resultSet.getString("UUID"));
10570    }
10571    } catch (SQLException e) {
10572  0 if (connection != null) {
10573  0 try {
10574  0 connection.rollback();
10575    } catch (SQLException ex) {
10576  0 handleException("Failed to rollback getting Block condition with id " + conditionId, ex);
10577    }
10578    }
10579  0 handleException("Failed to get Block condition with id " + conditionId, e);
10580    } finally {
10581  0 APIMgtDBUtil.closeAllConnections(selectPreparedStatement, connection, resultSet);
10582    }
10583  0 return blockCondition;
10584    }
10585   
10586    /**
10587    * Get details of a block condition by UUID
10588    *
10589    * @param uuid uuid of the block condition
10590    * @return Block conditoin represented by the UUID
10591    * @throws APIManagementException
10592    */
 
10593  0 toggle public BlockConditionsDTO getBlockConditionByUUID(String uuid) throws APIManagementException {
10594  0 Connection connection = null;
10595  0 PreparedStatement selectPreparedStatement = null;
10596  0 ResultSet resultSet = null;
10597  0 BlockConditionsDTO blockCondition = null;
10598  0 try {
10599  0 String query = SQLConstants.ThrottleSQLConstants.GET_BLOCK_CONDITION_BY_UUID_SQL;
10600  0 connection = APIMgtDBUtil.getConnection();
10601  0 connection.setAutoCommit(true);
10602  0 selectPreparedStatement = connection.prepareStatement(query);
10603  0 selectPreparedStatement.setString(1, uuid);
10604  0 resultSet = selectPreparedStatement.executeQuery();
10605  0 if (resultSet.next()) {
10606  0 blockCondition = new BlockConditionsDTO();
10607  0 blockCondition.setEnabled(resultSet.getBoolean("ENABLED"));
10608  0 blockCondition.setConditionType(resultSet.getString("TYPE"));
10609  0 blockCondition.setConditionValue(resultSet.getString("VALUE"));
10610  0 blockCondition.setConditionId(resultSet.getInt("CONDITION_ID"));
10611  0 blockCondition.setTenantDomain(resultSet.getString("DOMAIN"));
10612  0 blockCondition.setUUID(resultSet.getString("UUID"));
10613    }
10614    } catch (SQLException e) {
10615  0 if (connection != null) {
10616  0 try {
10617  0 connection.rollback();
10618    } catch (SQLException ex) {
10619  0 handleException("Failed to rollback getting Block condition by uuid " + uuid, ex);
10620    }
10621    }
10622  0 handleException("Failed to get Block condition by uuid " + uuid, e);
10623    } finally {
10624  0 APIMgtDBUtil.closeAllConnections(selectPreparedStatement, connection, resultSet);
10625    }
10626  0 return blockCondition;
10627    }
10628   
 
10629  0 toggle public List<BlockConditionsDTO> getBlockConditions(String tenantDomain) throws APIManagementException {
10630  0 Connection connection = null;
10631  0 PreparedStatement selectPreparedStatement = null;
10632  0 ResultSet resultSet = null;
10633  0 List<BlockConditionsDTO> blockConditionsDTOList = new ArrayList<BlockConditionsDTO>();
10634  0 try {
10635  0 String query = SQLConstants.ThrottleSQLConstants.GET_BLOCK_CONDITIONS_SQL;
10636  0 connection = APIMgtDBUtil.getConnection();
10637  0 connection.setAutoCommit(true);
10638  0 selectPreparedStatement = connection.prepareStatement(query);
10639  0 selectPreparedStatement.setString(1, tenantDomain);
10640  0 resultSet = selectPreparedStatement.executeQuery();
10641  0 while (resultSet.next()) {
10642  0 BlockConditionsDTO blockConditionsDTO = new BlockConditionsDTO();
10643  0 blockConditionsDTO.setEnabled(resultSet.getBoolean("ENABLED"));
10644  0 blockConditionsDTO.setConditionType(resultSet.getString("TYPE"));
10645  0 blockConditionsDTO.setConditionValue(resultSet.getString("VALUE"));
10646  0 blockConditionsDTO.setConditionId(resultSet.getInt("CONDITION_ID"));
10647  0 blockConditionsDTO.setUUID(resultSet.getString("UUID"));
10648  0 blockConditionsDTO.setTenantDomain(resultSet.getString("DOMAIN"));
10649  0 blockConditionsDTOList.add(blockConditionsDTO);
10650    }
10651    } catch (SQLException e) {
10652  0 if (connection != null) {
10653  0 try {
10654  0 connection.rollback();
10655    } catch (SQLException ex) {
10656  0 handleException("Failed to rollback getting Block conditions ", ex);
10657    }
10658    }
10659  0 handleException("Failed to get Block conditions", e);
10660    } finally {
10661  0 APIMgtDBUtil.closeAllConnections(selectPreparedStatement, connection, resultSet);
10662    }
10663  0 return blockConditionsDTOList;
10664    }
10665   
10666    /**
10667    * Update the block condition state true (Enabled) /false (Disabled) given the UUID
10668    *
10669    * @param conditionId id of the block condition
10670    * @param state blocking state
10671    * @return true if the operation was success
10672    * @throws APIManagementException
10673    */
 
10674  0 toggle public boolean updateBlockConditionState(int conditionId, String state) throws APIManagementException {
10675  0 Connection connection = null;
10676  0 PreparedStatement updateBlockConditionPreparedStatement = null;
10677  0 boolean status = false;
10678  0 try {
10679  0 String query = SQLConstants.ThrottleSQLConstants.UPDATE_BLOCK_CONDITION_STATE_SQL;
10680  0 connection = APIMgtDBUtil.getConnection();
10681  0 connection.setAutoCommit(false);
10682  0 updateBlockConditionPreparedStatement = connection.prepareStatement(query);
10683  0 updateBlockConditionPreparedStatement.setString(1, state.toUpperCase());
10684  0 updateBlockConditionPreparedStatement.setInt(2, conditionId);
10685  0 updateBlockConditionPreparedStatement.executeUpdate();
10686  0 connection.commit();
10687  0 status = true;
10688    } catch (SQLException e) {
10689  0 if (connection != null) {
10690  0 try {
10691  0 connection.rollback();
10692    } catch (SQLException ex) {
10693  0 handleException("Failed to rollback updating Block condition with condition id " + conditionId, ex);
10694    }
10695    }
10696  0 handleException("Failed to update Block condition with condition id " + conditionId, e);
10697    } finally {
10698  0 APIMgtDBUtil.closeAllConnections(updateBlockConditionPreparedStatement, connection, null);
10699    }
10700  0 return status;
10701    }
10702   
10703    /**
10704    * Update the block condition state true (Enabled) /false (Disabled) given the UUID
10705    *
10706    * @param uuid UUID of the block condition
10707    * @param state blocking state
10708    * @return true if the operation was success
10709    * @throws APIManagementException
10710    */
 
10711  0 toggle public boolean updateBlockConditionStateByUUID(String uuid, String state) throws APIManagementException {
10712  0 Connection connection = null;
10713  0 PreparedStatement updateBlockConditionPreparedStatement = null;
10714  0 boolean status = false;
10715  0 try {
10716  0 String query = SQLConstants.ThrottleSQLConstants.UPDATE_BLOCK_CONDITION_STATE_BY_UUID_SQL;
10717  0 connection = APIMgtDBUtil.getConnection();
10718  0 connection.setAutoCommit(false);
10719  0 updateBlockConditionPreparedStatement = connection.prepareStatement(query);
10720  0 updateBlockConditionPreparedStatement.setString(1, state.toUpperCase());
10721  0 updateBlockConditionPreparedStatement.setString(2, uuid);
10722  0 updateBlockConditionPreparedStatement.executeUpdate();
10723  0 connection.commit();
10724  0 status = true;
10725    } catch (SQLException e) {
10726  0 if (connection != null) {
10727  0 try {
10728  0 connection.rollback();
10729    } catch (SQLException ex) {
10730  0 handleException("Failed to rollback updating Block condition with condition UUID " + uuid, ex);
10731    }
10732    }
10733  0 handleException("Failed to update Block condition with condition UUID " + uuid, e);
10734    } finally {
10735  0 APIMgtDBUtil.closeAllConnections(updateBlockConditionPreparedStatement, connection, null);
10736    }
10737  0 return status;
10738    }
10739   
10740    /**
10741    * Delete the block condition given the id
10742    *
10743    * @param conditionId id of the condition
10744    * @return true if successfully deleted
10745    * @throws APIManagementException
10746    */
 
10747  0 toggle public boolean deleteBlockCondition(int conditionId) throws APIManagementException {
10748  0 Connection connection = null;
10749  0 PreparedStatement deleteBlockConditionPreparedStatement = null;
10750  0 boolean status = false;
10751  0 try {
10752  0 String query = SQLConstants.ThrottleSQLConstants.DELETE_BLOCK_CONDITION_SQL;
10753  0 connection = APIMgtDBUtil.getConnection();
10754  0 connection.setAutoCommit(false);
10755  0 deleteBlockConditionPreparedStatement = connection.prepareStatement(query);
10756  0 deleteBlockConditionPreparedStatement.setInt(1, conditionId);
10757  0 status = deleteBlockConditionPreparedStatement.execute();
10758  0 connection.commit();
10759  0 status = true;
10760    } catch (SQLException e) {
10761  0 if (connection != null) {
10762  0 try {
10763  0 connection.rollback();
10764    } catch (SQLException ex) {
10765  0 handleException("Failed to rollback deleting Block condition with condition id " + conditionId, ex);
10766    }
10767    }
10768  0 handleException("Failed to delete Block condition with condition id " + conditionId, e);
10769    } finally {
10770  0 APIMgtDBUtil.closeAllConnections(deleteBlockConditionPreparedStatement, connection, null);
10771    }
10772  0 return status;
10773    }
10774   
10775    /**
10776    * Delete the block condition given the id
10777    *
10778    * @param uuid UUID of the block condition
10779    * @return true if successfully deleted
10780    * @throws APIManagementException
10781    */
 
10782  0 toggle public boolean deleteBlockConditionByUUID(String uuid) throws APIManagementException {
10783  0 Connection connection = null;
10784  0 PreparedStatement deleteBlockConditionPreparedStatement = null;
10785  0 boolean status = false;
10786  0 try {
10787  0 String query = SQLConstants.ThrottleSQLConstants.DELETE_BLOCK_CONDITION_BY_UUID_SQL;
10788  0 connection = APIMgtDBUtil.getConnection();
10789  0 connection.setAutoCommit(false);
10790  0 deleteBlockConditionPreparedStatement = connection.prepareStatement(query);
10791  0 deleteBlockConditionPreparedStatement.setString(1, uuid);
10792  0 status = deleteBlockConditionPreparedStatement.execute();
10793  0 connection.commit();
10794  0 status = true;
10795    } catch (SQLException e) {
10796  0 if (connection != null) {
10797  0 try {
10798  0 connection.rollback();
10799    } catch (SQLException ex) {
10800  0 handleException("Failed to rollback deleting Block condition with condition UUID " + uuid, ex);
10801    }
10802    }
10803  0 handleException("Failed to delete Block condition with condition UUID " + uuid, e);
10804    } finally {
10805  0 APIMgtDBUtil.closeAllConnections(deleteBlockConditionPreparedStatement, connection, null);
10806    }
10807  0 return status;
10808    }
10809   
 
10810  0 toggle private boolean isValidContext(String context) throws APIManagementException {
10811  0 Connection connection = null;
10812  0 PreparedStatement validateContextPreparedStatement = null;
10813  0 ResultSet resultSet = null;
10814  0 boolean status = false;
10815  0 try {
10816  0 String query = "select count(*) COUNT from AM_API where CONTEXT=?";
10817  0 connection = APIMgtDBUtil.getConnection();
10818  0 connection.setAutoCommit(false);
10819  0 validateContextPreparedStatement = connection.prepareStatement(query);
10820  0 validateContextPreparedStatement.setString(1, context);
10821  0 resultSet = validateContextPreparedStatement.executeQuery();
10822  0 connection.commit();
10823  0 if (resultSet.next() && resultSet.getInt("COUNT") > 0) {
10824  0 status = true;
10825    }
10826    } catch (SQLException e) {
10827  0 if (connection != null) {
10828  0 try {
10829  0 connection.rollback();
10830    } catch (SQLException ex) {
10831  0 handleException("Failed to rollback checking Block condition with context " + context, ex);
10832    }
10833    }
10834  0 handleException("Failed to check Block condition with context " + context, e);
10835    } finally {
10836  0 APIMgtDBUtil.closeAllConnections(validateContextPreparedStatement, connection, resultSet);
10837    }
10838  0 return status;
10839    }
10840   
 
10841  0 toggle private boolean isValidApplication(String appOwner, String appName) throws APIManagementException {
10842  0 Connection connection = null;
10843  0 PreparedStatement validateContextPreparedStatement = null;
10844  0 ResultSet resultSet = null;
10845  0 boolean status = false;
10846  0 try {
10847  0 String query = "SELECT * FROM AM_APPLICATION App,AM_SUBSCRIBER SUB WHERE App.NAME=? AND App" +
10848    ".SUBSCRIBER_ID=SUB.SUBSCRIBER_ID AND SUB.USER_ID=?";
10849  0 connection = APIMgtDBUtil.getConnection();
10850  0 connection.setAutoCommit(false);
10851  0 validateContextPreparedStatement = connection.prepareStatement(query);
10852  0 validateContextPreparedStatement.setString(1, appName);
10853  0 validateContextPreparedStatement.setString(2, appOwner);
10854  0 resultSet = validateContextPreparedStatement.executeQuery();
10855  0 connection.commit();
10856  0 if (resultSet.next()) {
10857  0 status = true;
10858    }
10859    } catch (SQLException e) {
10860  0 if (connection != null) {
10861  0 try {
10862  0 connection.rollback();
10863    } catch (SQLException ex) {
10864  0 handleException(
10865    "Failed to rollback checking Block condition with Application Name " + appName + " with "
10866    + "Application Owner" + appOwner, ex);
10867    }
10868    }
10869  0 handleException("Failed to check Block condition with Application Name " + appName + " with " +
10870    "Application Owner" + appOwner, e);
10871    } finally {
10872  0 APIMgtDBUtil.closeAllConnections(validateContextPreparedStatement, connection, resultSet);
10873    }
10874  0 return status;
10875    }
10876   
 
10877  3389 toggle public String getAPILevelTier(int id) throws APIManagementException {
10878  3389 Connection connection = null;
10879  3389 PreparedStatement selectPreparedStatement = null;
10880  3389 ResultSet resultSet = null;
10881  3389 String apiLevelTier = null;
10882  3389 try {
10883  3389 String query = SQLConstants.GET_API_DETAILS_SQL;
10884  3389 connection = APIMgtDBUtil.getConnection();
10885  3389 connection.setAutoCommit(true);
10886  3389 selectPreparedStatement = connection.prepareStatement(query + " WHERE API_ID = ?");
10887  3389 selectPreparedStatement.setInt(1, id);
10888  3389 resultSet = selectPreparedStatement.executeQuery();
10889  6778 while (resultSet.next()) {
10890  3389 apiLevelTier = resultSet.getString("API_TIER");
10891    }
10892    } catch (SQLException e) {
10893  0 if (connection != null) {
10894  0 try {
10895  0 connection.rollback();
10896    } catch (SQLException ex) {
10897  0 handleException("Failed to rollback getting API Details", ex);
10898    }
10899    }
10900  0 handleException("Failed to get API Details", e);
10901    } finally {
10902  3389 APIMgtDBUtil.closeAllConnections(selectPreparedStatement, connection, resultSet);
10903    }
10904  3389 return apiLevelTier;
10905    }
10906   
 
10907  0 toggle private boolean isBlockConditionExist(String conditionType, String conditionValue, String tenantDomain, Connection
10908    connection) throws APIManagementException {
10909  0 PreparedStatement checkIsExistPreparedStatement = null;
10910  0 ResultSet checkIsResultSet = null;
10911  0 boolean status = false;
10912  0 try {
10913  0 String isExistQuery = SQLConstants.ThrottleSQLConstants.BLOCK_CONDITION_EXIST_SQL;
10914  0 checkIsExistPreparedStatement = connection.prepareStatement(isExistQuery);
10915  0 checkIsExistPreparedStatement.setString(1, tenantDomain);
10916  0 checkIsExistPreparedStatement.setString(2, conditionType);
10917  0 checkIsExistPreparedStatement.setString(3, conditionValue);
10918  0 checkIsResultSet = checkIsExistPreparedStatement.executeQuery();
10919  0 connection.commit();
10920  0 if (checkIsResultSet.next()) {
10921  0 status = true;
10922    }
10923    } catch (SQLException e) {
10924  0 String msg = "Couldn't check the Block Condition Exist";
10925  0 log.error(msg, e);
10926  0 handleException(msg, e);
10927    } finally {
10928  0 APIMgtDBUtil.closeAllConnections(checkIsExistPreparedStatement, null, checkIsResultSet);
10929    }
10930  0 return status;
10931    }
10932   
 
10933  0 toggle public boolean hasSubscription(String tierId, String tenantDomainWithAt, String policyLevel) throws APIManagementException {
10934  0 PreparedStatement checkIsExistPreparedStatement = null;
10935  0 Connection connection = null;
10936  0 ResultSet checkIsResultSet = null;
10937  0 boolean status = false;
10938  0 try {
10939    /*String apiProvider = tenantId;*/
10940  0 connection = APIMgtDBUtil.getConnection();
10941  0 connection.setAutoCommit(true);
10942  0 String isExistQuery = SQLConstants.ThrottleSQLConstants.TIER_HAS_SUBSCRIPTION;
10943  0 if (PolicyConstants.POLICY_LEVEL_API.equals(policyLevel)) {
10944  0 isExistQuery = SQLConstants.ThrottleSQLConstants.TIER_ATTACHED_TO_RESOURCES_API;
10945  0 } else if (PolicyConstants.POLICY_LEVEL_APP.equals(policyLevel)) {
10946  0 isExistQuery = SQLConstants.ThrottleSQLConstants.TIER_ATTACHED_TO_APPLICATION;
10947  0 } else if (PolicyConstants.POLICY_LEVEL_SUB.equals(policyLevel)) {
10948  0 isExistQuery = SQLConstants.ThrottleSQLConstants.TIER_HAS_SUBSCRIPTION;
10949    }
10950   
10951  0 checkIsExistPreparedStatement = connection.prepareStatement(isExistQuery);
10952  0 checkIsExistPreparedStatement.setString(1, tierId);
10953  0 checkIsExistPreparedStatement.setString(2, "%" + tenantDomainWithAt);
10954  0 if (PolicyConstants.POLICY_LEVEL_API.equals(policyLevel)) {
10955  0 checkIsExistPreparedStatement.setString(3, tierId);
10956  0 checkIsExistPreparedStatement.setString(4, "%" + tenantDomainWithAt);
10957    }
10958  0 checkIsResultSet = checkIsExistPreparedStatement.executeQuery();
10959  0 if (checkIsResultSet != null && checkIsResultSet.next()) {
10960  0 int count = checkIsResultSet.getInt(1);
10961  0 if (count > 0) {
10962  0 status = true;
10963    }
10964   
10965    }
10966   
10967  0 connection.setAutoCommit(true);
10968    } catch (SQLException e) {
10969  0 String msg = "Couldn't check Subscription Exist";
10970  0 log.error(msg, e);
10971  0 handleException(msg, e);
10972    } finally {
10973  0 APIMgtDBUtil.closeAllConnections(checkIsExistPreparedStatement, connection, checkIsResultSet);
10974    }
10975  0 return status;
10976   
10977    }
10978   
10979   
10980    /**
10981    * Get a list of access tokens issued for given user under the given app of given owner. Returned object carries
10982    * consumer key and secret information related to the access token
10983    *
10984    * @param userName end user name
10985    * @param appName application name
10986    * @param appOwner application owner user name
10987    * @return list of tokens
10988    * @throws SQLException in case of a DB issue
10989    */
 
10990  0 toggle public static List<AccessTokenInfo> getAccessTokenListForUser(String userName, String appName, String appOwner)
10991    throws SQLException {
10992  0 List<AccessTokenInfo> accessTokens = new ArrayList<AccessTokenInfo>(5);
10993  0 Connection connection = APIMgtDBUtil.getConnection();
10994  0 PreparedStatement consumerSecretIDPS = connection.prepareStatement(SQLConstants.GET_ACCESS_TOKENS_BY_USER_SQL);
10995  0 consumerSecretIDPS.setString(1, userName);
10996  0 consumerSecretIDPS.setString(2, appName);
10997  0 consumerSecretIDPS.setString(3, appOwner);
10998   
10999  0 ResultSet consumerSecretIDResult = consumerSecretIDPS.executeQuery();
11000   
11001  0 while (consumerSecretIDResult.next()) {
11002  0 String consumerKey = consumerSecretIDResult.getString(1);
11003  0 String consumerSecret = consumerSecretIDResult.getString(2);
11004  0 String accessToken = consumerSecretIDResult.getString(3);
11005   
11006  0 AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
11007  0 accessTokenInfo.setConsumerKey(consumerKey);
11008  0 accessTokenInfo.setConsumerSecret(consumerSecret);
11009  0 accessTokenInfo.setAccessToken(accessToken);
11010   
11011  0 accessTokens.add(accessTokenInfo);
11012    }
11013   
11014  0 return accessTokens;
11015    }
11016   
 
11017  4 toggle public String[] getAPIDetailsByContext(String context) {
11018  4 String apiName = "";
11019  4 String apiProvider = "";
11020  4 String sql = SQLConstants.GET_API_FOR_CONTEXT_TEMPLATE_SQL;
11021  4 Connection conn = null;
11022  4 PreparedStatement ps = null;
11023  4 ResultSet rs = null;
11024  4 try {
11025  4 conn = APIMgtDBUtil.getConnection();
11026  4 conn.setAutoCommit(true);
11027  4 ps = conn.prepareStatement(sql);
11028  4 ps.setString(1, context);
11029   
11030  4 rs = ps.executeQuery();
11031  4 if (rs.next()) {
11032  0 apiName = rs.getString("API_NAME");
11033  0 apiProvider = rs.getString("API_PROVIDER");
11034    }
11035    } catch (SQLException e) {
11036  0 log.error("Error occurred while fetching data: " + e.getMessage(), e);
11037    } finally {
11038  4 try {
11039  4 conn.setAutoCommit(false);
11040    } catch (SQLException e) {
11041  0 log.error("Error occurred while fetching data: " + e.getMessage(), e);
11042    }
11043  4 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
11044    }
11045  4 return new String[]{apiName, apiProvider};
11046    }
11047   
11048    /**
11049    * Check for the subscription of the user
11050    *
11051    * @param infoDTO
11052    * @param context
11053    * @param version
11054    * @param consumerKey
11055    * @return APIKeyValidationInfoDTO including data of api and application
11056    * @throws APIManagementException
11057    */
 
11058  4 toggle public APIKeyValidationInfoDTO validateSubscriptionDetails(APIKeyValidationInfoDTO infoDTO,
11059    String context, String version,
11060    String consumerKey,
11061    boolean defaultVersionInvoked)
11062    throws APIManagementException {
11063  4 String apiTenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(context);
11064  4 if (apiTenantDomain == null) {
11065  2 apiTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
11066    }
11067   
11068  4 int apiOwnerTenantId = APIUtil.getTenantIdFromTenantDomain(apiTenantDomain);
11069  4 String sql;
11070  4 boolean isAdvancedThrottleEnabled = APIUtil.isAdvanceThrottlingEnabled();
11071  4 if (!isAdvancedThrottleEnabled) {
11072  0 if (defaultVersionInvoked) {
11073  0 sql = SQLConstants.VALIDATE_SUBSCRIPTION_KEY_DEFAULT_SQL;
11074    } else {
11075  0 sql = SQLConstants.VALIDATE_SUBSCRIPTION_KEY_VERSION_SQL;
11076    }
11077    } else {
11078  4 if (defaultVersionInvoked) {
11079  0 sql = SQLConstants.ADVANCED_VALIDATE_SUBSCRIPTION_KEY_DEFAULT_SQL;
11080    } else {
11081  4 sql = SQLConstants.ADVANCED_VALIDATE_SUBSCRIPTION_KEY_VERSION_SQL;
11082    }
11083    }
11084   
11085  4 Connection conn = null;
11086  4 PreparedStatement ps = null;
11087  4 ResultSet rs = null;
11088  4 try {
11089  4 conn = APIMgtDBUtil.getConnection();
11090  4 conn.setAutoCommit(true);
11091  4 ps = conn.prepareStatement(sql);
11092  4 ps.setString(1, context);
11093  4 ps.setString(2, consumerKey);
11094  4 if (!defaultVersionInvoked) {
11095  4 ps.setString(3, version);
11096    }
11097   
11098  4 rs = ps.executeQuery();
11099  4 if (rs.next()) {
11100  4 String subscriptionStatus = rs.getString("SUB_STATUS");
11101  4 String type = rs.getString("KEY_TYPE");
11102  4 if (APIConstants.SubscriptionStatus.BLOCKED.equals(subscriptionStatus)) {
11103  0 infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_BLOCKED);
11104  0 infoDTO.setAuthorized(false);
11105  0 return infoDTO;
11106  4 } else if (APIConstants.SubscriptionStatus.ON_HOLD.equals(subscriptionStatus) ||
11107    APIConstants.SubscriptionStatus.REJECTED.equals(subscriptionStatus)) {
11108  0 infoDTO.setValidationStatus(
11109    APIConstants.KeyValidationStatus.SUBSCRIPTION_INACTIVE);
11110  0 infoDTO.setAuthorized(false);
11111  0 return infoDTO;
11112  4 } else if (APIConstants.SubscriptionStatus.PROD_ONLY_BLOCKED
11113    .equals(subscriptionStatus) &&
11114    !APIConstants.API_KEY_TYPE_SANDBOX.equals(type)) {
11115  0 infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_BLOCKED);
11116  0 infoDTO.setType(type);
11117  0 infoDTO.setAuthorized(false);
11118  0 return infoDTO;
11119    }
11120   
11121  4 String tokenType = rs.getString("TOKEN_TYPE");
11122  4 if (APIConstants.JWT.equals(tokenType)) {
11123  0 infoDTO.setAuthorized(false);
11124  0 return infoDTO;
11125    }
11126   
11127  4 final String API_PROVIDER = rs.getString("API_PROVIDER");
11128  4 final String SUB_TIER = rs.getString("TIER_ID");
11129  4 final String APP_TIER = rs.getString("APPLICATION_TIER");
11130  4 infoDTO.setTier(SUB_TIER);
11131  4 infoDTO.setSubscriber(rs.getString("USER_ID"));
11132  4 infoDTO.setApplicationId(rs.getString("APPLICATION_ID"));
11133  4 infoDTO.setApiName(rs.getString("API_NAME"));
11134  4 infoDTO.setApiPublisher(API_PROVIDER);
11135  4 infoDTO.setApplicationName(rs.getString("NAME"));
11136  4 infoDTO.setApplicationTier(APP_TIER);
11137  4 infoDTO.setType(type);
11138   
11139    //Advanced Level Throttling Related Properties
11140  4 if (APIUtil.isAdvanceThrottlingEnabled()) {
11141  4 String apiTier = rs.getString("API_TIER");
11142  4 String subscriberUserId = rs.getString("USER_ID");
11143  4 String subscriberTenant = MultitenantUtils.getTenantDomain(subscriberUserId);
11144  4 int apiId = rs.getInt("API_ID");
11145  4 int subscriberTenantId = APIUtil.getTenantId(subscriberUserId);
11146  4 int apiTenantId = APIUtil.getTenantId(API_PROVIDER);
11147    //TODO isContentAware
11148  4 boolean isContentAware =
11149    isAnyPolicyContentAware(conn, apiTier, APP_TIER, SUB_TIER,
11150    subscriberTenantId, apiTenantId, apiId);
11151  4 infoDTO.setContentAware(isContentAware);
11152   
11153    //TODO this must implement as a part of throttling implementation.
11154  4 int spikeArrest = 0;
11155  4 String apiLevelThrottlingKey = "api_level_throttling_key";
11156  4 if (rs.getInt("RATE_LIMIT_COUNT") > 0) {
11157  0 spikeArrest = rs.getInt("RATE_LIMIT_COUNT");
11158    }
11159   
11160  4 String spikeArrestUnit = null;
11161  4 if (rs.getString("RATE_LIMIT_TIME_UNIT") != null) {
11162  0 spikeArrestUnit = rs.getString("RATE_LIMIT_TIME_UNIT");
11163    }
11164  4 boolean stopOnQuotaReach = rs.getBoolean("STOP_ON_QUOTA_REACH");
11165  4 List<String> list = new ArrayList<String>();
11166  4 list.add(apiLevelThrottlingKey);
11167  4 infoDTO.setSpikeArrestLimit(spikeArrest);
11168  4 infoDTO.setSpikeArrestUnit(spikeArrestUnit);
11169  4 infoDTO.setStopOnQuotaReach(stopOnQuotaReach);
11170  4 infoDTO.setSubscriberTenantDomain(subscriberTenant);
11171  4 if (apiTier != null && apiTier.trim().length() > 0) {
11172  2 infoDTO.setApiTier(apiTier);
11173    }
11174    //We also need to set throttling data list associated with given API. This need to have policy id and
11175    // condition id list for all throttling tiers associated with this API.
11176  4 infoDTO.setThrottlingDataList(list);
11177    }
11178  4 infoDTO.setAuthorized(true);
11179  4 return infoDTO;
11180    }
11181  0 infoDTO.setAuthorized(false);
11182  0 infoDTO.setValidationStatus(
11183    APIConstants.KeyValidationStatus.API_AUTH_RESOURCE_FORBIDDEN);
11184    } catch (SQLException e) {
11185  0 handleException("Exception occurred while validating Subscription.", e);
11186    } finally {
11187  4 try {
11188  4 conn.setAutoCommit(false);
11189    } catch (SQLException e) {
11190  0 log.error("Error occurred while fetching data: " + e.getMessage(), e);
11191    }
11192  4 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
11193    }
11194  0 return infoDTO;
11195    }
11196   
11197    /**
11198    * Returns a Prepared statement after setting all the dynamic parameters. Dynamic parameters will be added in
11199    * the place of $params in query string
11200    *
11201    * @param conn connection which will be used to create a prepared statement
11202    * @param query dynamic query string which will be modified.
11203    * @param params list of parameters
11204    * @param startingParamIndex index from which the parameter numbering will start.
11205    * @return
11206    * @throws SQLException
11207    */
 
11208  0 toggle public PreparedStatement fillQueryParams(Connection conn, String query, String params[], int startingParamIndex)
11209    throws SQLException {
11210   
11211  0 String paramString = "";
11212   
11213  0 for (int i = 1; i <= params.length; i++) {
11214  0 if (i == params.length) {
11215  0 paramString = paramString + "?";
11216    } else {
11217  0 paramString = paramString + "?,";
11218    }
11219    }
11220   
11221  0 query = query.replace("$params", paramString);
11222   
11223  0 if (log.isDebugEnabled()) {
11224  0 log.info("Prepared statement query :" + query);
11225    }
11226   
11227  0 PreparedStatement preparedStatement = conn.prepareStatement(query);
11228  0 for (int i = 0; i < params.length; i++) {
11229  0 preparedStatement.setString(startingParamIndex, params[i]);
11230  0 startingParamIndex++;
11231    }
11232  0 return preparedStatement;
11233    }
11234   
11235    /**
11236    * Returns True if AM_APPLICATION_GROUP_MAPPING table exist in AM DB
11237    *
11238    * @return
11239    */
 
11240  0 toggle public boolean isGrpIdMappingTableExist() {
11241   
11242  0 String sql = "SELECT * FROM AM_APPLICATION_GROUP_MAPPING";
11243  0 Connection conn = null;
11244  0 PreparedStatement ps = null;
11245  0 ResultSet rs = null;
11246  0 try {
11247  0 conn = APIMgtDBUtil.getConnection();
11248  0 ps = conn.prepareStatement(sql);
11249   
11250  0 rs = ps.executeQuery();
11251   
11252    } catch (SQLException e) {
11253  0 log.info("AM_APPLICATION_GROUP_MAPPING :- " + e.getMessage(), e);
11254  0 return false;
11255    } finally {
11256   
11257  0 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
11258    }
11259  0 return true;
11260    }
11261   
11262    /**
11263    * Adds a new record in AM_APPLICATION_GROUP_MAPPING for each group
11264    *
11265    * @param conn
11266    * @param applicationId
11267    * @param groupIdString group id values separated by commas
11268    * @return
11269    * @throws APIManagementException
11270    */
 
11271  0 toggle private boolean updateGroupIDMappings(Connection conn, int applicationId, String groupIdString, String tenant)
11272    throws APIManagementException {
11273   
11274  0 boolean updateSuccessful = false;
11275   
11276  0 PreparedStatement removeMigratedGroupIdsStatement = null;
11277  0 PreparedStatement deleteStatement = null;
11278  0 PreparedStatement insertStatement = null;
11279  0 String deleteQuery = SQLConstants.REMOVE_GROUP_ID_MAPPING_SQL;
11280  0 String insertQuery = SQLConstants.ADD_GROUP_ID_MAPPING_SQL;
11281   
11282  0 try {
11283    // Remove migrated Group ID information so that it can be replaced by updated Group ID's that are now
11284    // being saved. This is done to ensure that there is no conflicting migrated Group ID data remaining
11285  0 removeMigratedGroupIdsStatement = conn.prepareStatement(SQLConstants.REMOVE_MIGRATED_GROUP_ID_SQL);
11286  0 removeMigratedGroupIdsStatement.setInt(1, applicationId);
11287  0 removeMigratedGroupIdsStatement.executeUpdate();
11288   
11289  0 deleteStatement = conn.prepareStatement(deleteQuery);
11290  0 deleteStatement.setInt(1, applicationId);
11291  0 deleteStatement.executeUpdate();
11292   
11293  0 if (!StringUtils.isEmpty(groupIdString)) {
11294   
11295  0 String[] groupIdArray = groupIdString.split(",");
11296   
11297  0 insertStatement = conn.prepareStatement(insertQuery);
11298  0 for (String group : groupIdArray) {
11299  0 insertStatement.setInt(1, applicationId);
11300  0 insertStatement.setString(2, group);
11301  0 insertStatement.setString(3, tenant);
11302  0 insertStatement.addBatch();
11303    }
11304  0 insertStatement.executeBatch();
11305    }
11306  0 updateSuccessful = true;
11307    } catch (SQLException e) {
11308  0 updateSuccessful = false;
11309  0 handleException("Failed to update GroupId mappings ", e);
11310    } finally {
11311  0 APIMgtDBUtil.closeAllConnections(removeMigratedGroupIdsStatement, null, null);
11312  0 APIMgtDBUtil.closeAllConnections(deleteStatement, null, null);
11313  0 APIMgtDBUtil.closeAllConnections(insertStatement, null, null);
11314    }
11315  0 return updateSuccessful;
11316    }
11317   
11318    /**
11319    * Fetches all the groups for a given application and creates a single string separated by comma
11320    *
11321    * @param applicationId
11322    * @return comma separated group Id String
11323    * @throws APIManagementException
11324    */
 
11325  0 toggle public String getGroupId(int applicationId) throws APIManagementException {
11326   
11327  0 String grpId = "";
11328  0 ArrayList<String> grpIdList = new ArrayList<String>();
11329  0 PreparedStatement preparedStatement = null;
11330  0 Connection conn = null;
11331  0 ResultSet resultSet = null;
11332  0 String sqlQuery = SQLConstants.GET_GROUP_ID_SQL;
11333   
11334  0 try {
11335  0 conn = APIMgtDBUtil.getConnection();
11336  0 preparedStatement = conn.prepareStatement(sqlQuery);
11337  0 preparedStatement.setInt(1, applicationId);
11338  0 resultSet = preparedStatement.executeQuery();
11339   
11340  0 while (resultSet.next()) {
11341  0 grpIdList.add(resultSet.getString("GROUP_ID"));
11342    }
11343   
11344  0 for (int i = 0; i < grpIdList.size(); i++) {
11345  0 if (i == grpIdList.size() - 1) {
11346  0 grpId = grpId + grpIdList.get(i);
11347    } else {
11348  0 grpId = grpId + grpIdList.get(i) + ",";
11349    }
11350    }
11351   
11352    } catch (SQLException e) {
11353  0 handleException("Failed to Retrieve GroupId for application " + applicationId, e);
11354    } finally {
11355  0 APIMgtDBUtil.closeAllConnections(preparedStatement, conn, resultSet);
11356    }
11357  0 return grpId;
11358    }
11359   
11360    /**
11361    * Get access token information associated with the given consumer key.
11362    *
11363    * @param consumerKey The consumer key.
11364    * @return APIKey The access token information.
11365    * @throws SQLException
11366    * @throws CryptoException
11367    */
 
11368  300 toggle public APIKey getAccessTokenInfoByConsumerKey(String consumerKey) throws SQLException, CryptoException,
11369    APIManagementException {
11370   
11371  300 String accessTokenStoreTable = APIConstants.ACCESS_TOKEN_STORE_TABLE;
11372  300 String username = getUserIdFromConsumerKey(consumerKey);
11373  300 accessTokenStoreTable = getAccessTokenStoreTableNameOfUserId(username, accessTokenStoreTable);
11374   
11375  300 Connection connection = null;
11376  300 PreparedStatement preparedStatement = null;
11377  300 ResultSet resultSet = null;
11378   
11379  300 String statement = SQLConstants.GET_ACCESS_TOKEN_INFO_BY_CONSUMER_KEY_PREFIX +
11380    accessTokenStoreTable + SQLConstants.GET_ACCESS_TOKEN_INFO_BY_CONSUMER_KEY_SUFFIX;
11381   
11382  300 String oracleSQL = SQLConstants.GET_ACCESS_TOKEN_INFO_BY_CONSUMER_KEY_ORACLE_PREFIX +
11383    accessTokenStoreTable + SQLConstants.GET_ACCESS_TOKEN_INFO_BY_CONSUMER_KEY_ORACLE_SUFFIX;
11384   
11385  300 String mySQL = "SELECT" + statement;
11386  300 String db2SQL = "SELECT" + statement;
11387  300 String msSQL = "SELECT " + statement;
11388  300 String postgreSQL = "SELECT * FROM (SELECT" + statement + ") AS TOKEN";
11389   
11390  300 String accessToken;
11391  300 String sql;
11392   
11393  300 try {
11394  300 connection = APIMgtDBUtil.getConnection();
11395   
11396  300 if (connection.getMetaData().getDriverName().contains("MySQL") || connection.getMetaData().getDriverName
11397    ().contains("H2")) {
11398  300 sql = mySQL;
11399  0 } else if (connection.getMetaData().getDatabaseProductName().contains("DB2")) {
11400  0 sql = db2SQL;
11401  0 } else if (connection.getMetaData().getDriverName().contains("MS SQL") || connection.getMetaData()
11402    .getDriverName().contains("Microsoft")) {
11403  0 sql = msSQL;
11404  0 } else if (connection.getMetaData().getDriverName().contains("PostgreSQL")) {
11405  0 sql = postgreSQL;
11406    } else {
11407  0 sql = oracleSQL;
11408    }
11409   
11410  300 preparedStatement = connection.prepareStatement(sql);
11411  300 preparedStatement.setString(1, consumerKey);
11412  300 preparedStatement.setString(2, APIConstants.ACCESS_TOKEN_USER_TYPE_APPLICATION);
11413  300 resultSet = preparedStatement.executeQuery();
11414  300 if (resultSet.next()) {
11415  300 APIKey apiKey = new APIKey();
11416  300 accessToken = APIUtil.decryptToken(resultSet.getString("ACCESS_TOKEN"));
11417  300 apiKey.setConsumerKey(consumerKey);
11418  300 String consumerSecret = resultSet.getString("CONSUMER_SECRET");
11419  300 apiKey.setConsumerSecret(APIUtil.decryptToken(consumerSecret));
11420  300 apiKey.setAccessToken(accessToken);
11421  300 apiKey.setValidityPeriod(resultSet.getLong("VALIDITY_PERIOD") / 1000);
11422  300 apiKey.setGrantTypes(resultSet.getString("GRANT_TYPES"));
11423  300 apiKey.setCallbackUrl(resultSet.getString("CALLBACK_URL"));
11424   
11425    // Load all the rows to in memory and build the scope string
11426  300 List<String> scopes = new ArrayList<String>();
11427  300 String tokenString = resultSet.getString("ACCESS_TOKEN");
11428   
11429  300 do {
11430  600 String currentRowTokenString = resultSet.getString("ACCESS_TOKEN");
11431  600 if (tokenString.equals(currentRowTokenString)) {
11432  600 scopes.add(resultSet.getString(APIConstants.IDENTITY_OAUTH2_FIELD_TOKEN_SCOPE));
11433    }
11434  600 } while (resultSet.next());
11435  300 apiKey.setTokenScope(getScopeString(scopes));
11436  300 return apiKey;
11437    }
11438  0 return null;
11439    } finally {
11440  300 APIMgtDBUtil.closeAllConnections(preparedStatement, connection, resultSet);
11441    }
11442    }
11443   
11444    /**
11445    * Returns the user id for the consumer key.
11446    *
11447    * @param consumerKey The consumer key.
11448    * @return String The user id.
11449    */
 
11450  300 toggle private String getUserIdFromConsumerKey(String consumerKey) throws APIManagementException {
11451  300 Connection connection = null;
11452  300 PreparedStatement prepStmt = null;
11453  300 ResultSet rs = null;
11454  300 String userId = null;
11455   
11456  300 String sqlQuery = SQLConstants.GET_USER_ID_FROM_CONSUMER_KEY_SQL;
11457   
11458  300 try {
11459  300 connection = APIMgtDBUtil.getConnection();
11460  300 prepStmt = connection.prepareStatement(sqlQuery);
11461  300 prepStmt.setString(1, consumerKey);
11462  300 rs = prepStmt.executeQuery();
11463   
11464  600 while (rs.next()) {
11465  300 userId = rs.getString("USER_ID");
11466    }
11467   
11468    } catch (SQLException e) {
11469  0 handleException("Error when getting the user id for Consumer Key" + consumerKey, e);
11470    } finally {
11471  300 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
11472    }
11473  300 return userId;
11474    }
11475   
11476    /**
11477    * Get Subscribed APIs for an App.
11478    *
11479    * @param applicationName id of the application name
11480    * @return APISubscriptionInfoDTO[]
11481    * @throws APIManagementException if failed to get Subscribed APIs
11482    */
 
11483  4 toggle public APISubscriptionInfoDTO[] getSubscribedAPIsForAnApp(String userId, String applicationName) throws
11484    APIManagementException {
11485  4 List<APISubscriptionInfoDTO> apiSubscriptionInfoDTOS = new ArrayList<APISubscriptionInfoDTO>();
11486  4 Connection conn = null;
11487  4 PreparedStatement ps = null;
11488  4 ResultSet rs = null;
11489   
11490    //identify logged in user
11491  4 String loginUserName = getLoginUserName(userId);
11492  4 int tenantId = APIUtil.getTenantId(loginUserName);
11493   
11494  4 String sqlQuery = SQLConstants.GET_SUBSCRIBED_APIS_OF_USER_BY_APP_SQL;
11495  4 if (forceCaseInsensitiveComparisons) {
11496  4 sqlQuery = SQLConstants.GET_SUBSCRIBED_APIS_OF_USER_BY_APP_CASE_INSENSITIVE_SQL;
11497    }
11498   
11499  4 try {
11500  4 conn = APIMgtDBUtil.getConnection();
11501  4 ps = conn.prepareStatement(sqlQuery);
11502  4 ps.setInt(1, tenantId);
11503  4 ps.setString(2, applicationName);
11504  4 rs = ps.executeQuery();
11505  8 while (rs.next()) {
11506  4 APISubscriptionInfoDTO infoDTO = new APISubscriptionInfoDTO();
11507  4 infoDTO.setProviderId(APIUtil.replaceEmailDomain(rs.getString("API_PROVIDER")));
11508  4 infoDTO.setApiName(rs.getString("API_NAME"));
11509  4 infoDTO.setContext(rs.getString("API_CONTEXT"));
11510  4 infoDTO.setVersion(rs.getString("API_VERSION"));
11511  4 infoDTO.setSubscriptionTier(rs.getString("SP_TIER_ID"));
11512  4 apiSubscriptionInfoDTOS.add(infoDTO);
11513    }
11514    } catch (SQLException e) {
11515  0 handleException("Error while executing SQL", e);
11516    } finally {
11517  4 APIMgtDBUtil.closeAllConnections(ps, conn, rs);
11518    }
11519  4 return apiSubscriptionInfoDTOS.toArray(new APISubscriptionInfoDTO[apiSubscriptionInfoDTOS.size()]);
11520    }
11521   
11522   
 
11523  399 toggle public Application getApplicationByClientId(String clientId) throws APIManagementException {
11524  399 Connection connection = null;
11525  399 PreparedStatement prepStmt = null;
11526  399 ResultSet rs = null;
11527   
11528  399 Application application = null;
11529  399 try {
11530  399 connection = APIMgtDBUtil.getConnection();
11531  399 String query = SQLConstants.GET_APPLICATION_BY_CLIENT_ID_SQL;
11532   
11533  399 prepStmt = connection.prepareStatement(query);
11534  399 prepStmt.setString(1, clientId);
11535   
11536  399 rs = prepStmt.executeQuery();
11537  399 if (rs.next()) {
11538  262 String applicationId = rs.getString("APPLICATION_ID");
11539  262 String applicationName = rs.getString("NAME");
11540  262 String applicationOwner = rs.getString("CREATED_BY");
11541   
11542  262 application = new Application(applicationId);
11543  262 application.setName(applicationName);
11544  262 application.setOwner(applicationOwner);
11545  262 application.setDescription(rs.getString("DESCRIPTION"));
11546  262 application.setStatus(rs.getString("APPLICATION_STATUS"));
11547  262 application.setCallbackUrl(rs.getString("CALLBACK_URL"));
11548  262 application.setId(rs.getInt("APPLICATION_ID"));
11549  262 application.setGroupId(rs.getString("GROUP_ID"));
11550  262 application.setUUID(rs.getString("UUID"));
11551  262 application.setTier(rs.getString("APPLICATION_TIER"));
11552  262 application.setTokenType(rs.getString("TOKEN_TYPE"));
11553  262 application.setKeyType(rs.getString("KEY_TYPE"));
11554   
11555  262 if (multiGroupAppSharingEnabled) {
11556  0 if (application.getGroupId().isEmpty()) {
11557  0 application.setGroupId(getGroupId(application.getId()));
11558    }
11559    }
11560    }
11561    } catch (SQLException e) {
11562  0 handleException("Error while obtaining details of the Application foe client id " + clientId, e);
11563    } finally {
11564  399 APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
11565    }
11566  399 return application;
11567    }
11568   
11569    /**
11570    * Returns the Label List for the TenantId.
11571    *
11572    * @param tenantDomain The tenant domain.
11573    * @return List of labels.
11574    */
 
11575  824 toggle public List<Label> getAllLabels(String tenantDomain) throws APIManagementException {
11576  824 List<Label> labelList = new ArrayList<>();
11577   
11578  824 try (Connection connection = APIMgtDBUtil.getConnection();
11579  824 PreparedStatement statement = connection.prepareStatement(SQLConstants.GET_LABEL_BY_TENANT)) {
11580  824 try {
11581  824 connection.setAutoCommit(false);
11582  824 statement.setString(1, tenantDomain);
11583  824 try (ResultSet rs = statement.executeQuery()) {
11584  824 while (rs.next()) {
11585  0 String labelId = rs.getString("LABEL_ID");
11586  0 String labelName = rs.getString("NAME");
11587  0 String description = rs.getString("DESCRIPTION");
11588   
11589  0 Label label = new Label();
11590  0 label.setLabelId(labelId);
11591  0 label.setName(labelName);
11592  0 label.setDescription(description);
11593  0 label.setAccessUrls(getAccessUrlList(connection, labelId));
11594  0 labelList.add(label);
11595    }
11596    }
11597  824 connection.commit();
11598    } catch (SQLException e) {
11599  0 connection.rollback();
11600  0 handleException("Failed to get Labels of " + tenantDomain, e);
11601    } finally {
11602  824 connection.setAutoCommit(true);
11603    }
11604    } catch (SQLException e) {
11605  0 handleException("Failed to get Labels of " + tenantDomain, e);
11606    }
11607  824 return labelList;
11608    }
11609   
11610    /**
11611    * Returns the URL list for label id.
11612    *
11613    * @param labelId label id.
11614    * @return List of string.
11615    */
 
11616  0 toggle private List<String> getAccessUrlList(Connection connection, String labelId) throws APIManagementException {
11617  0 List<String> hostList = new ArrayList<>();
11618   
11619  0 try (PreparedStatement statement = connection.prepareStatement(SQLConstants.GET_URL_BY_LABEL_ID)) {
11620  0 statement.setString(1, labelId);
11621  0 try (ResultSet rs = statement.executeQuery()) {
11622  0 while (rs.next()) {
11623  0 String host = rs.getString("ACCESS_URL");
11624  0 hostList.add(host);
11625    }
11626    }
11627    } catch (SQLException e) {
11628  0 handleException("Failed to get label list: " , e);
11629    }
11630  0 return hostList;
11631    }
11632   
11633    /**
11634    * Returns the Label.
11635    *
11636    * @param tenantDomain The tenant domain.
11637    * @param label label object.
11638    * @return label.
11639    */
 
11640  0 toggle public Label addLabel(String tenantDomain, Label label) throws APIManagementException {
11641  0 String uuid = UUID.randomUUID().toString();
11642  0 label.setLabelId(uuid);
11643  0 try (Connection connection = APIMgtDBUtil.getConnection();
11644  0 PreparedStatement statement = connection.prepareStatement(SQLConstants.ADD_LABEL_SQL)) {
11645  0 try {
11646  0 initialAutoCommit = connection.getAutoCommit();
11647  0 connection.setAutoCommit(false);
11648   
11649  0 statement.setString(1, uuid);
11650  0 statement.setString(2, label.getName());
11651  0 statement.setString(3, label.getDescription());
11652  0 statement.setString(4, tenantDomain);
11653  0 statement.executeUpdate();
11654  0 if (!label.getAccessUrls().isEmpty()) {
11655  0 insertAccessUrlMappings(connection, uuid, label.getAccessUrls());
11656    }
11657  0 connection.commit();
11658    } catch (SQLException e) {
11659  0 connection.rollback();
11660  0 handleException("Failed to add label: " + uuid, e);
11661    } finally {
11662  0 APIMgtDBUtil.setAutoCommit(connection, initialAutoCommit);
11663    }
11664    } catch (SQLException e) {
11665  0 handleException("Failed to add label: " + uuid, e);
11666    }
11667  0 return label;
11668    }
11669   
11670    /**
11671    * Insert URL to the URL table
11672    *
11673    * @param uuid label id.
11674    * @param urlList The list of url.
11675    * @throws APIManagementException
11676    */
 
11677  0 toggle private void insertAccessUrlMappings(Connection connection, String uuid, List<String> urlList) throws
11678    APIManagementException {
11679  0 try (PreparedStatement statement = connection.prepareStatement(SQLConstants.ADD_LABEL_URL_MAPPING_SQL)) {
11680  0 for (String accessUrl : urlList) {
11681  0 statement.setString(1, uuid);
11682  0 statement.setString(2, accessUrl);
11683  0 statement.addBatch();
11684    }
11685  0 statement.executeBatch();
11686    } catch (SQLException e) {
11687  0 handleException("Failed to add label url : " + uuid, e);
11688    }
11689    }
11690   
11691    /**
11692    * Delete label.
11693    *
11694    * @param labelUUID label id.
11695    * @throws APIManagementException
11696    */
 
11697  0 toggle public void deleteLabel(String labelUUID) throws APIManagementException {
11698   
11699  0 try (Connection connection = APIMgtDBUtil.getConnection();
11700  0 PreparedStatement statement = connection.prepareStatement(SQLConstants.DELETE_LABEL_SQL)) {
11701  0 try {
11702  0 initialAutoCommit = connection.getAutoCommit();
11703  0 connection.setAutoCommit(false);
11704  0 statement.setString(1, labelUUID);
11705  0 statement.executeUpdate();
11706  0 connection.commit();
11707    } catch (SQLException e) {
11708  0 connection.rollback();
11709  0 handleException("Failed to delete label : " + labelUUID, e);
11710    } finally {
11711  0 APIMgtDBUtil.setAutoCommit(connection, initialAutoCommit);
11712    }
11713    } catch (SQLException e) {
11714  0 handleException("Failed to delete label : " + labelUUID, e);
11715    }
11716    }
11717   
11718    /**
11719    * Delete label URL
11720    *
11721    * @param labelUUID label id.
11722    * @throws APIManagementException
11723    */
 
11724  0 toggle private void deleteAccessUrlMappings(Connection connection, String labelUUID) throws APIManagementException {
11725  0 try (PreparedStatement statement = connection.prepareStatement(SQLConstants.DELETE_LABEL_URL_MAPPING_SQL)) {
11726  0 statement.setString(1, labelUUID);
11727  0 statement.executeUpdate();
11728    } catch (SQLException e) {
11729  0 handleException("Failed to delete label url : ", e);
11730    }
11731    }
11732   
11733    /**
11734    * Update the label.
11735    *
11736    * @param label label object.
11737    * @return labels.
11738    */
 
11739  0 toggle public Label updateLabel(Label label) throws APIManagementException {
11740  0 List<String> accessURLs = label.getAccessUrls();
11741  0 try (Connection connection = APIMgtDBUtil.getConnection();
11742  0 PreparedStatement statement = connection.prepareStatement(SQLConstants.UPDATE_LABEL_SQL)) {
11743  0 try {
11744  0 initialAutoCommit = connection.getAutoCommit();
11745  0 connection.setAutoCommit(false);
11746  0 statement.setString(1, label.getName());
11747  0 statement.setString(2, label.getDescription());
11748  0 statement.setString(3, label.getLabelId());
11749   
11750  0 deleteAccessUrlMappings(connection, label.getLabelId());
11751  0 insertAccessUrlMappings(connection, label.getLabelId(), accessURLs);
11752  0 statement.executeUpdate();
11753  0 connection.commit();
11754    } catch (SQLException e) {
11755  0 connection.rollback();
11756  0 handleException("Failed to update label : ", e);
11757    } finally {
11758  0 APIMgtDBUtil.setAutoCommit(connection, initialAutoCommit);
11759    }
11760    } catch (SQLException e) {
11761  0 handleException("Failed to update label : ", e);
11762    }
11763  0 return label;
11764    }
11765   
 
11766  310 toggle private void addApplicationAttributes(Connection conn, Map<String, String> attributes, int applicationId, int tenantId)
11767    throws APIManagementException {
11768   
11769  310 PreparedStatement ps = null;
11770  310 ResultSet rs = null;
11771  310 try {
11772  310 if(attributes != null) {
11773  310 ps = conn.prepareStatement(SQLConstants.ADD_APPLICATION_ATTRIBUTES_SQL);
11774  310 for (String key : attributes.keySet()) {
11775  4 ps.setInt(1, applicationId);
11776  4 ps.setString(2, key);
11777  4 ps.setString(3, attributes.get(key));
11778  4 ps.setInt(4, tenantId);
11779  4 ps.addBatch();
11780    }
11781  310 int[] update = ps.executeBatch();
11782    }
11783    } catch (SQLException e) {
11784  0 handleException("Error in adding attributes of application with id: " + applicationId , e);
11785    } finally {
11786  310 APIMgtDBUtil.closeAllConnections(ps, null, rs);
11787    }
11788    }
11789   
11790    /**
11791    * Get all attributes stored against an Application
11792    *
11793    * @param conn Database connection
11794    * @param applicationId
11795    * @throws APIManagementException
11796    */
 
11797  1465 toggle public Map<String, String> getApplicationAttributes(Connection conn, int applicationId) throws APIManagementException {
11798   
11799  1465 PreparedStatement ps = null;
11800  1465 ResultSet rs = null;
11801  1465 Map<String, String> applicationAttributes = new HashMap<>();
11802  1465 try {
11803  1465 ps = conn.prepareStatement(SQLConstants.GET_APPLICATION_ATTRIBUTES_BY_APPLICATION_ID);
11804  1465 ps.setInt(1, applicationId);
11805  1465 rs = ps.executeQuery();
11806  1483 while (rs.next()) {
11807  18 applicationAttributes.put(rs.getString("NAME"),
11808    rs.getString("VALUE"));
11809    }
11810   
11811    } catch (SQLException e) {
11812  0 handleException("Error when reading attributes of application with id: " + applicationId, e);
11813    } finally {
11814  1465 APIMgtDBUtil.closeAllConnections(ps, null, rs);
11815    }
11816  1465 return applicationAttributes;
11817    }
11818   
11819    /**
11820    * Delete certain attribute stored against an Application
11821    *
11822    * @param attributeKey User defined key of attribute
11823    * @param applicationId
11824    * @throws APIManagementException
11825    */
 
11826  4 toggle public void deleteApplicationAttributes(String attributeKey, int applicationId) throws APIManagementException {
11827   
11828  4 Connection connection = null;
11829  4 PreparedStatement ps = null;
11830   
11831  4 try {
11832  4 connection = APIMgtDBUtil.getConnection();
11833  4 connection.setAutoCommit(false);
11834  4 ps = connection.prepareStatement(SQLConstants.REMOVE_APPLICATION_ATTRIBUTES_BY_ATTRIBUTE_NAME_SQL);
11835  4 ps.setString(1, attributeKey);
11836  4 ps.setInt(2, applicationId);
11837  4 ps.execute();
11838  4 connection.commit();
11839    } catch (SQLException e) {
11840  0 handleException("Error in establishing SQL connection ", e);
11841    } finally {
11842  4 APIMgtDBUtil.closeAllConnections(ps, connection, null);
11843    }
11844    }
11845   
11846    /**
11847    * Add new attributes against an Application in API Store
11848    *
11849    * @param applicationAttributes Map of key, value pair of attributes
11850    * @param applicationId Id of Application against which attributes are getting stored
11851    * @param tenantId Id of tenant
11852    * @throws APIManagementException
11853    */
 
11854  153 toggle public void addApplicationAttributes(Map<String, String> applicationAttributes, int applicationId, int tenantId)
11855    throws APIManagementException {
11856   
11857  153 Connection connection = null;
11858  153 try {
11859  153 connection = APIMgtDBUtil.getConnection();
11860  153 connection.setAutoCommit(false);
11861  153 addApplicationAttributes(connection, applicationAttributes, applicationId, tenantId);
11862  153 connection.commit();
11863    } catch (SQLException sqlException) {
11864  0 if (connection != null) {
11865  0 try {
11866  0 connection.rollback();
11867    } catch (SQLException e) {
11868  0 log.error("Failed to rollback add application attributes ", e);
11869    }
11870    }
11871  0 handleException("Failed to add Application", sqlException);
11872    } finally {
11873  153 APIMgtDBUtil.closeAllConnections(null, connection, null);
11874    }
11875    }
11876    }